// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('ydApp', [
    'ionic',
    'ngCordova',
    'ionic-native-transitions',
    'angular-carousel',
    'angular.filter',
    'ydApp.login',
    'ydApp.home',
    'ydApp.chat',
    'ydApp.check',
    'ydApp.user',
    // 'ydApp.user.info',
    'ydApp.user.center',
    'ydApp.register',
    'ydApp.doc',
    'ydApp.clinic',
    'ydApp.classRoom',
    'ydApp.health'
])

.run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
            if (window.cordova && window.cordova.plugins.Keyboard) {
                // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                // for form inputs)
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                // Don't remove this line unless you know what you are doing. It stops the viewport
                // from snapping when text inputs are focused. Ionic handles this internally for
                // a much nicer keyboard experience.
                cordova.plugins.Keyboard.disableScroll(true);
                //延迟splash screnn 隐藏时间,不然会有短暂的白屏出现  
                setTimeout(function() {
                    navigator.splashscreen.hide();
                }, 500);
            }
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }
        });
    })
    .run(function(appInit) {
        appInit.init();
    })
    .config(function($urlRouterProvider,$sceDelegateProvider, $httpProvider, $stateProvider, $ionicConfigProvider, $ionicNativeTransitionsProvider) {
        $ionicNativeTransitionsProvider.setDefaultOptions({
            duration: 400, // in milliseconds (ms), default 400,
            slowdownfactor: 4, // overlap views (higher number is more) or no overlap (1), default 4
            iosdelay: -1, // ms to wait for the iOS webview to update before animation kicks in, default -1
            androiddelay: -1, // same as above but for Android, default -1
            winphonedelay: -1, // same as above but for Windows Phone, default -1,
            fixedPixelsTop: 0, // the number of pixels of your fixed header, default 0 (iOS and Android)
            fixedPixelsBottom: 0, // the number of pixels of your fixed footer (f.i. a tab bar), default 0 (iOS and Android)
            triggerTransitionEvent: '$ionicView.afterEnter', // internal ionic-native-transitions option
            backInOppositeDirection: false // Takes over default back transition and state back transition to use the opposite direction transition to go back
        });
        $ionicNativeTransitionsProvider.setDefaultTransition({
            type: 'slide',
            direction: 'left'
        });
        $ionicNativeTransitionsProvider.setDefaultBackTransition({
            type: 'slide',
            direction: 'right'
        });
        $ionicConfigProvider.views.transition('ios');
        $ionicConfigProvider.tabs.style('standard').position('bottom');
        $ionicConfigProvider.navBar.alignTitle('center').positionPrimaryButtons('left');


        $sceDelegateProvider.resourceUrlWhitelist([
            // Allow same origin resource loads.
            'self',
            // Allow loading from our assets domain.  Notice the difference between * and **.
            config.api + '**'
        ]);


        $stateProvider.state('tabs', {
            abstract: true,
            url: '/tab',
            templateUrl: 'views/tabs.html'
        });
        $urlRouterProvider.otherwise(function($injector) {
            var $state = $injector.get("$state");
            $state.go("tabs.home");
        });
        $httpProvider.interceptors.push('ydFilter');
    });

var config = {
    // api: "http://180.153.67.8:9090/",
    api: "http://115.28.128.133:8080/",
    loginWhiteList: {
        "login": true,
        'loading': true,
        "register":true,
        "resetPwd":true,
        "register-user": true,
        "register-doc":true,
        "register-doc-info":true,
        "register-doc-info-hospital":true,
        "register-doc-info-depart":true,
        "register-doc-info-position":true,
        "register-doc-info-succ":true,
        "register-noduty":true
    },
    userDocState: {
        'tabs.user': true,
        'userInfo':true,
        'tabs.recent-chat': true,
        'tabs.recent-check': true
    }

};

(function() {
    'use strict';
    angular.module('ydApp')
        .factory('ydFilter', function($location, localStore) {
            return {
                request: function(req) {

                    return req;
                },
                responseError: function(response) {
                    console.log(JSON.stringify(response))
                    return response;
                }
            };
        })
        .factory('cardCodeFilter', function(){
            return function(input){
                if(input)
                {
                    var code="**** **** **** ";
                    code=code+input.substring(input.length-4);
                    return code;
                }
            };
        })
        .factory('cardEndFilter', function(){
            return function(input){
                if(input)
                {
                    var code="尾号";
                    code=code+input.substring(input.length-4);
                    return code;
                }
            };
        })
})();


(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('appInit', appInit);

    function appInit(localStore, $state, $ionicPlatform, $rootScope, xhr, userService, chatInterval, $timeout, $ionicHistory) {
        function init() {
            var isStart = localStore.get('isStart');
            $rootScope.downloadImg = function(img) {
                return config.api + "HealthInquiry/" + img;
            }

           
            $rootScope.go = function(router) {
                $state.go(router);
            }
            $ionicPlatform.on("resume", function(event) {});
            $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, formParams) {

                var path = "";
                for (var i = 0; i < $state.$current.path.length; i++) {
                    path += $state.$current.path[i].url.source + "--->";
                }
                isStart = localStore.get('isStart');
                if (toState != 'chat') {
                    clearInterval(chatInterval.interval)
                }
                if (!isStart && toState.name != "loading") {
                    $state.go('loading');
                    event.preventDefault();
                    return;
                }

                var user = localStore.get("user");
                var userType = localStore.get("userType");




                if (user && angular.equals(toState.name, 'login')) {
                    $state.go("tabs.home");
                    event.preventDefault();
                    return;
                } else if (!user && !config.loginWhiteList[toState.name]) {
                    $state.go("login");
                    event.preventDefault();
                    return;
                }

                // if (toState.name == "other-hospital" && fromState.name == "select-hospital") {
                //  $state.go("user-info");
                //  event.preventDefault();
                //  return;
                // };
                if (config.userDocState[toState.name]) {
                    //医生帐号
                    if (userType == 2) {
                        console.log("jump to doctor");
                        $state.go(toState.name + "-doc");
                        event.preventDefault();
                        return;
                    }
                }
                if (fromState.name === 'register-doc-info-succ' && toState.name === 'register-doc-info') {
                    $state.go('login');
                    event.preventDefault();
                    return;
                }
            });
        }
        return {
            init: init
        };
    }
})();
(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('userService', userService);

    function userService(xhr, $q, localStore) {
        var userInfo = {};

        function get(userId) {
            var defer = $q.defer();

            return defer.promise;
        }

        return {
            get: get,
            userInfo: userInfo
        }
    }
})();

(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('popup', function($ionicPopup, $ionicActionSheet) {
            function alert(msg) {
                return $ionicPopup.alert({
                    template: msg,
                    cssClass: 'yd-popup',
                    okText: "确认"
                })
            }

            function confirm(content, okText, cancelText) {
                return $ionicPopup.confirm({
                    template: content,
                    cssClass: 'yd-popup',
                    okText: okText || "确认",
                    cancelText: cancelText || "取消"
                });
            }

            function sheet(title, buttons, callback, cancelCallBack) {
                $ionicActionSheet.show({
                    buttons: buttons,
                    titleText: title,
                    cancelText: "取消",
                    cancel: function() {
                        if (cancelCallBack) {
                            cancelCallBack();
                        }
                    },
                    buttonClicked: function(index) {
                        if (callback) {
                            callback(index)
                        }
                        return true;
                    }
                });
            }
            return {
                alert: alert,
                sheet: sheet,
                confirm: confirm
            }
        })
})();
(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('guid', function() {
            function Guid() {
                return (((1 + Math.random()) * 0x10000) | 0)
                    .toString(16)
                    .substring(1);
            }

            function get() {
                return Guid() + Guid();
            }
            return {
                get: get
            }
        })
})();
(function() {
    'user strict';
    angular
        .module("ydApp")
        .factory("localStore", function() {
            function save(key, data) {
                window.localStorage[key] = JSON.stringify(data);
            }

            function del(key) {
                window.localStorage.removeItem(key);
            }

            function get(key) {
                var data = window.localStorage[key] || '';
                if (data) {
                    return eval("(" + data + ")");
                }
                return null;
            }

            function clear() {
                for (var local in window.localStorage) {
                    window.localStorage.removeItem(local);
                };
                alert("清除成功");
                window.location.reload();
            }
            return {
                save: save,
                get: get,
                del: del,
                clear: clear
            }
        })
})();

(function() {
    'use strict';
    angular
        .module('ydApp')
        .factory('xhr', xhrService, ['$http', '$q']);

    function xhrService($http, $q, popup, $ionicLoading) {
        function post(routeName, params) {
            params = params || {};
            var deferred = $q.defer();
            $http({
                    method: "POST",
                    url: config.api + routeName,
                    data: params
                })
                .then(function(response) {
                    $ionicLoading.hide();
                    if (response.data.successful) {
                        deferred.resolve(response.data);
                    } else {
                        popupError(response.data.resultMsg)
                        deferred.reject(response.data.resultMsg);
                    }
                }, function(err) {
                    $ionicLoading.hide();
                    deferred.reject(err);
                })
            return deferred.promise;
        }

        function get(routeName, params, noPopup) {
            var strParams = "?";
            for (var key in params) {
                if (params[key] == null) {
                    continue;
                }
                strParams += key + "=" + params[key] + "&";
            }
            if (strParams.length > 1) {
                strParams = strParams.substring(0, strParams.length - 1);
            }
            var url = config.api + routeName + strParams;
            var deferred = $q.defer();
            $http({
                    method: "GET",
                    url: url
                })
                .then(function(response) {
                    $ionicLoading.hide();
                    if (response.data.successful) {
                        deferred.resolve(response.data);
                    } else {
                        if (!noPopup) {
                            popupError(response.data.resultMsg)
                        }
                        deferred.reject(response.data);
                    }
                }, function(err) {
                    $ionicLoading.hide();
                    deferred.reject(err);
                })
            return deferred.promise;
        }

        function popupError(responseCode) {
            popup.alert(responseCode)
        }

        return {
            post: post,
            get: get
        };
    }
})();



(function() {
    'use strict';
    angular
        .module('ydApp')
        .factory('Cameranav', Cameranav);

    function Cameranav($cordovaCamera, $ionicPlatform, popup) {
        function getByPhoto(successCall, errorCall) {
            get(successCall, errorCall, {
                quality: 70,
                destinationType: 1,
                sourceType: 0,
                allowEdit: false,
                encodingType: 0,
                saveToPhotoAlbum: false,
                targetWidth: 1000,
                targetHeight: 1000,
                mediaType: 0
            });
        }

        function getByVideo(successCall, errorCall) {
            get(successCall, errorCall, {
                quality: 70,
                destinationType: 1,
                sourceType: 0,
                encodingType: 0,
                saveToPhotoAlbum: false,
                targetWidth: 1000,
                targetHeight: 1000,
                mediaType: 1
            });
        }

        function getByCamera(successCall, errorCall) {
            get(successCall, errorCall, {
                destinationType: 1,
                sourceType: 1,
                encodingType: 0,
                saveToPhotoAlbum: false
            });
        }

        function get(successCall, errorCall, options) {
            if (window.cordova) {
                $ionicPlatform.ready(function() {
                    $cordovaCamera.getPicture(options).then(function(imageUri) {
                        console.log(imageUri)
                        if (successCall) {
                            successCall(imageUri);
                        }
                    }, function(err) {
                        console.log("err:" + err)
                        if (errorCall) {
                            errorCall(err);
                        }
                    });
                });
            } else {
                if (successCall) {
                    successCall("uploadImg");
                }
            }
        }

        function getPicture(successCall, errorCall) {
            popup.sheet("选择图片", [
                { text: "相册" },
                { text: "相机" }
            ], function(index) {
                if (index == 0) {
                    getByPhoto(successCall, errorCall);
                } else {
                    getByCamera(successCall, errorCall);
                }
            })
        }

        function getSource(successCall, errorCall) {
            console.log("sss")
            popup.sheet("选择图片", [
                { text: "相册" },
                { text: "视频" },
                { text: "相机" }
            ], function(index) {
                if (index == 0) {
                    getByPhoto(successCall, errorCall);
                } else if (index == 1) {
                    getByVideo(function(uri) {
                        successCall(uri, true);
                    }, errorCall);
                } else {
                    getByCamera(successCall, errorCall);
                }
            })
        }
        return {
            getPicture: getPicture,
            getSource: getSource
        }
    }
})();


(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('fileTransfer', fileTransfer);

    function fileTransfer($ionicPlatform, $cordovaFileTransfer, xhr, localStore) {
        function upload(uri, id, successCall, errorCall, progressCall) {
            if (window.cordova) {
                $ionicPlatform.ready(function() {
                    var imageUpload = config.api + "HealthInquiry/com/uploadImage?id=" + id;
                    var params = new Object();

                    $cordovaFileTransfer.upload(imageUpload, uri, params)
                        .then(function(result) {
                            console.log(JSON.stringify(result))
                            successCall(eval("(" + result.response + ")"));
                        }, function(err) {
                            console.log(JSON.stringify(err))
                            if (errorCall) {
                                errorCall(err);
                            };
                        }, function(progress) {
                            if (progressCall) {
                                progressCall(progress);
                            };
                        });
                });
            } else {
                successCall({ fileName: uri });
            }
        }
        return {
            upload: upload
        };
    }
})();


(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('datePicker', datePicker);

    function datePicker($cordovaDatePicker, $ionicPlatform) {
        function show(callback, type) {
            if (window.cordova) {
                $ionicPlatform.ready(function() {
                    var options = {
                        date: new Date("1990-01-01"),
                        mode: type || 'date', // or 'time'
                        doneButtonLabel: '确认',
                        doneButtonColor: '#000000',
                        cancelButtonLabel: '取消',
                        cancelButtonColor: '#000000',
                        locale: "zh-cn"
                    };
                    $cordovaDatePicker.show(options).then(function(date) {
                        callback(getDateFormat(date, type || 'date'));
                    });
                });
            } else {
                callback(getDateFormat(new Date()));
            }
        }

        function getDateFormat(date, type) {
            if (type = "date") {
                return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            } else {
                return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
            }

        }
        return {
            show: show
        }
    }
})();


(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('geoService', geoService);

    function geoService($cordovaGeolocation, $ionicPlatform, Wgs2Mars, $q) {
        function get(callback) {
            var defer = $q.defer();
            if (window.cordova) {
                $ionicPlatform.ready(function() {
                    var posOptions = {
                        maximumAge: 3000,
                        timeout: 5000,
                        enableHighAccuracy: true
                    };
                    $cordovaGeolocation.getCurrentPosition(posOptions).then(function(position) {
                        var loc = Wgs2Mars.transform(
                            position.coords.longitude,
                            position.coords.latitude);
                        defer.resolve({
                            lng: loc.lng,
                            lat: loc.lat
                        })
                    }, function(err) {
                        console.error(JSON.stringify(err))
                        defer.reject(err);
                    });
                });
            } else {
                defer.resolve({
                    lng: "118.769417",
                    lat: "32.04737"
                })
            }
            return defer.promise;
        }
        return {
            get: get
        };
    }
})();



(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('Wgs2Mars', Wgs2Mars);

    function Wgs2Mars() {

        var PI = 3.14159265358979324;
        var a = 6378245.0;
        var ee = 0.00669342162296594323;

        function Rectangle(lng1, lat1, lng2, lat2) {
            this.west = Math.min(lng1, lng2);
            this.north = Math.max(lat1, lat2);
            this.east = Math.max(lng1, lng2);
            this.south = Math.min(lat1, lat2);
        }

        function isInRect(rect, lon, lat) {
            return rect.west <= lon && rect.east >= lon && rect.north >= lat && rect.south <= lat;
        }
        //China region - raw data
        var region = [
            new Rectangle(79.446200, 49.220400, 96.330000, 42.889900),
            new Rectangle(109.687200, 54.141500, 135.000200, 39.374200),
            new Rectangle(73.124600, 42.889900, 124.143255, 29.529700),
            new Rectangle(82.968400, 29.529700, 97.035200, 26.718600),
            new Rectangle(97.025300, 29.529700, 124.367395, 20.414096),
            new Rectangle(107.975793, 20.414096, 111.744104, 17.871542)
        ];
        //China excluded region - raw data
        var exclude = [
            new Rectangle(119.921265, 25.398623, 122.497559, 21.785006),
            new Rectangle(101.865200, 22.284000, 106.665000, 20.098800),
            new Rectangle(106.452500, 21.542200, 108.051000, 20.487800),
            new Rectangle(109.032300, 55.817500, 119.127000, 50.325700),
            new Rectangle(127.456800, 55.817500, 137.022700, 49.557400),
            new Rectangle(131.266200, 44.892200, 137.022700, 42.569200)
        ];

        function isInChina(lon, lat) {
            for (var i = 0; i < region.length; i++) {
                if (isInRect(region[i], lon, lat)) {
                    for (var j = 0; j < exclude.length; j++) {
                        if (isInRect(exclude[j], lon, lat)) {
                            return false;
                        }
                    }
                    return true;
                }
            }
            return false;
        }

        function transformLat(x, y) {
            var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
            ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
            ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
            return ret;
        }

        function transformLon(x, y) {
            var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
            ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
            ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
            return ret;
        }

        // World Geodetic System ==> Mars Geodetic System
        function transform(wgLon, wgLat) {
            var mgLoc = {};
            if (!isInChina(wgLon, wgLat)) {
                mgLoc = {
                    lat: wgLat,
                    lng: wgLon
                };
                return mgLoc;
            }
            var dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
            var dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
            var radLat = wgLat / 180.0 * PI;
            var magic = Math.sin(radLat);
            magic = 1 - ee * magic * magic;
            var sqrtMagic = Math.sqrt(magic);
            dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
            dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
            mgLoc = {
                lat: wgLat + dLat,
                lng: wgLon + dLon
            };
            return mgLoc;
        }
        return {
            transform: transform
        };
    };
})();



(function() {
    'use strict'
    angular
        .module('ydApp')
        .service('chatInterval', chatInterval);

    function chatInterval() {
        this.interval = {};
    }
})();

(function() {
    'use strict'
    angular.module('ydApp')
        .factory('pay', pay);

    function pay($cordovaToast) {

        function alipay(subject, body, price, tradeNo, successCall, errorCall) {
            var myDate = new Date();
            var alipay = navigator.alipay;
            console.log(subject);
            console.log(body);
            console.log(price);
            console.log(tradeNo);

            alipay.pay({
                "seller": "nanjingeasygoing@163.com",
                // "seller": "3023819262@qq.com",
                "subject": subject,
                "body": body,
                "price": price,
                "tradeNo": tradeNo,
                "timeout": '30m',
                "notifyUrl": config.api + "HealthInquiry/com/alipay/getAliPay"
            }, function(resultStatus) {
                if (successCall) {
                    successCall(resultStatus)
                }
                console.log(resultStatus);
            }, function(message) {
                if (errorCall) {
                    errorCall(message);
                }
                $cordovaToast.showShortCenter("支付失败，请稍后再试");
                console.log(message);
            });
        }
        return {
            alipay: alipay
        };
    }


})();

(function() {
    angular
        .module('ydApp')
        .directive('imagePurview', function($ionicModal, $ionicSlideBoxDelegate , $ionicScrollDelegate, $rootScope) {
            return {
                restrict: "EA",
                scope:{
                    data: '='
                },
                link: function($scope, elem, attr, ngModel) {
                    $scope.$watch('data', function () {
                        $scope.images = $scope.data.images;
                    }, true);
                    $scope.downloadImg = $rootScope.downloadImg;
                    $scope.zoomMin = 1;
                    $scope.activeSlide = 1;
                    $scope.data.showImage = function (index) {
                        $scope.activeSlide = index;
                        $ionicModal.fromTemplateUrl('directive/imagePurview/imagePurview.html', {
                            scope: $scope,
                            animation: 'slide-in-up'
                        }).then(function(modal) {
                            $scope.modal = modal;
                            $scope.modal.show();
                        });
                    }
                    // Close the modal
                    $scope.closeModal = function() {
                        $scope.modal.hide();
                        $scope.modal.remove()
                    };
                    $scope.updateSlideStatus = function(slide) {
                      var zoomFactor = $ionicScrollDelegate.$getByHandle('scrollHandle' + slide).getScrollPosition().zoom;
                      if (zoomFactor == $scope.zoomMin) {
                        $ionicSlideBoxDelegate.enableSlide(true);
                      } else {
                        $ionicSlideBoxDelegate.enableSlide(false);
                      }
                    }; 
                }
            };
        })
})();

(function() {
	angular
		.module('ydApp')
		.directive('calendar', function($timeout) {
			return {
				restrict: "EA",
				templateUrl: 'directive/calendar/calendar.html',
				replace: true,
				scope: {
					list: "=",
					date: "="
				},
				controller: function($scope, bdCalendar) {
					$scope.bdCalendar = bdCalendar;
				},
				link: function($scope, elem, attr) {
					var nowDate = new Date();
					var date = new Date();
					$scope.swipeLeft = function () {
						if (date.getMonth() - nowDate.getMonth() < 1) {
							console.log('swipeLeft');
							date.setMonth(date.getMonth()+1);
							init(date);
						}
					}
					$scope.swipeRight = function () {
						if (nowDate.getMonth() - date.getMonth() < 1) {
							console.log('swipeRight');
							date.setMonth(date.getMonth()-1);
							init(date);
						}
					}
					
					function init(now) {
						$timeout(function() {
							
							$scope.bdCalendar.init(now, function(date) {
								console.log(date)
								$(".today").removeClass('today');
								$("[data-id=" + date + "]").addClass("today");
								$scope.$apply(function() {
									$scope.date = date;
								})
							});
							if ($scope.list) {
								for (var i = 0; i < $scope.list.length; i++) {
									var day = new Date($scope.list[i]);
									var dataId = day.getFullYear() + '-' + (day.getMonth() + 1) + '-' + day.getDate();
									if (day.getDate() < now.getDate()) {
										$("[data-id=" + dataId + "]").addClass('day-yz before');
									} else {
										$("[data-id=" + dataId + "]").addClass('day-yz');
									}
								}
							}
							var loc = 7 - $("#cm>.week-row:first-child>.cell-num").length;
							$scope.ml = (loc * 14.2) + '%';
							$scope.month = now.getMonth() + 1;
						}, 100)
					}
					$scope.$watch('list', function () {
						init(date);
					}, true)
					

				}
			};
		})
})();
(function () {
	angular
	.module('ydApp')
	.directive('messageList', function () {
		return {
			restrict: "EA",
			templateUrl: 'directive/messageList/messageList.html',
			replace: true,
			require: "ngModel",
			scope: {
				call: "=",
				docHead: "=",
				head: '=',
				topTitle: '='
			},
			controller: function ($scope, localStore, $state, $ionicModal) {
				var vm = $scope.vm = {};
				vm.user = localStore.get('user');
				vm.userType = localStore.get("userType");
				//return '/img/icon-hos.jpg';
				vm.isPost = $state.current.name == 'post-chat';
				vm.avatarImg = function (userId) {
					if (userId) {
						return config.api + "HealthInquiry/" + vm.user.headImgUrl;
					} else {
						if (vm.userType == 2) {
							return config.api + "HealthInquiry/" + $scope.head;
						} else {
							return config.api + "HealthInquiry/" + $scope.docHead;
						}
					}
				}
				vm.downloadImg  = function (img) {
					return config.api + "HealthInquiry/" + img;
				}
				var maxHeight = 200;
				vm.loadImg = function (msg) {
					(function (load) {
						load(msg);
					})(function (m) {
						var img = new Image();
						img.src = config.api + "HealthInquiry/" + m.content;
						img.onload = function () {
							var winWidth = (window.screen.width-10) * 0.83 - 32-50;
							var width = img.width;
							var height = img.height;
							if (width > winWidth) {
								width = winWidth;
								console.log(width)
								height = (width/img.width)*height;
								if (height > maxHeight) {
									height = maxHeight;
									width = (height/img.height)*img.width;
								}
							} 
							m.imgWidth = width;
							m.imgHeight = height;
							m.chatImg = img.src;
						}
					})
				}
				vm.ipData = {}
				$scope.showImages = function (img) {
					vm.ipData.images = [img];
					vm.ipData.showImage(0);
				}
				
			},
			link: function ($scope, elem, attr, ngModel) {
				var vm = $scope.vm;
				ngModel.$render = function () {
					vm.msgs = ngModel.$viewValue;
				}
			}
		};
	})
})();
(function () {
	"use strict"
	angular
	.module('ydApp')
	.directive("infiniteList", infiniteList);

	function infiniteList ($timeout) {
		return{
		    transclude: true,
		    scope: {
		      scroll: '&',
		      infiniteScrollDistance: '='
		    },
    		template: '<div ng-transclude style="float:left;width: 100%;"></div>',
    		link: function (scope, elem) {
    			if (scope.infiniteScrollDistance === undefined) {
			    	scope.infiniteScrollDistance = 0;
			    }
			    var loading = false;
		        var container = $(elem).find(">div");
		        $(window).resize(function () {
		        	console.log("resize");
		        })
		        elem.on("scroll", function (event) {
		        	if (loading) {
		        		return;
		        	};
		        	if ($(elem).scrollTop() <= scope.infiniteScrollDistance) {
		        		loading = true;
		        		var height = $(container).height();
		        		var result = scope.scroll();
		        		(function (resortPosition) {
		        			if (result && typeof result.then === 'function') {
				              	result.then(resortPosition);
				            } else {
				              	resortPosition();
				            }
		        		})(function () {
		        			$timeout(function () {
			        			$(elem).scrollTop($(elem).scrollTop()+$(container).height() - height);
	           					loading = false;
			        		}, 0)
		        		})
		        	};
		        })
    		}
		}
	}
})();
(function() {
    angular
        .module('ydApp')
        .directive('navButton', function() {
            return {
                restrict: "EA",
                template: '<button class="button" ng-transclude></button>',
                replace: true,
                transclude: true,
                controller: function($scope, $location, $ionicHistory,$state) {
                    $scope.link = function(url) {
                        $location.url(url);
                    }
                    $scope.back = function(url) {
                        if ($scope.confirm) {
                            var result = $scope.confirm();
                            if (result != null) {
                                console.log(result)
                                result.then(function(res) {
                                    if (res) {
                                        $ionicHistory.goBack();
                                    }
                                })
                            } else {
                                $ionicHistory.goBack();
                            }
                        } else {
                            if (url) {
                                $state.go(url);
                            }
                            else {
                                $ionicHistory.goBack();
                            }
                        }

                    }
                }
            };
        })
})();

(function() {
    angular
        .module('ydApp')
        .directive('tabs', function() {
            return {
                restrict: "EA",
                templateUrl: 'directive/tabs/tabs.html',
                controller: function($scope, $location, $ionicHistory,$state) {
                    
                }
            };
        })
})();

(function () {
	angular
	.module('ydApp.chat', [])
	.config(function ($stateProvider) {
		$stateProvider.state('chat', {
			url: '/chat?docId?chatId?state?docHead?head',
			controller: "chatCtrl",
			cache: false,
			templateUrl: 'views/chats/chat.html'
		});
		
	})
	.controller("chatCtrl", chatCtrl);

	function chatCtrl ($scope, popup, xhr, localStore, $stateParams, reverseFilter, $timeout, $anchorScroll, Cameranav, $ionicLoading, fileTransfer, $q, chatInterval, $ionicHistory) {
		var vm = $scope.vm = {};
		vm.docHead = $stateParams.docHead;
		vm.head = $stateParams.head;
		vm.chatId = '';
		vm.user = localStore.get("user");
		vm.userType = localStore.get("userType");
		vm.queryStartTime = "";
		vm.queryEndTime = "";
		vm.msgs = [];
		vm.confirm = function () {
			if (vm.message.length > 0) {
				return popup.confirm('当前有消息尚未发送，是否取消发送?');
			} else {
				return null;
			}
		}
		vm.over = function () {
			popup.confirm('您正在结束本次咨询，结束后，患者将不能继续发送消息，是否立即结束?').then(function (res) {
				if (res) {
					xhr.get('HealthInquiry/com/call/overCall', {
						id: vm.chatId,
						toUser: vm.user.id
					}).then(function (res) {
						vm.call.state = 2;
						popup.alert('咨询成功结束').then(function () {
							$ionicHistory.goBack();
						});
					})
				}
			});
		}
		vm.loadMsg = function() {
			return xhr.get('HealthInquiry/com/callMsg/callMsgs', {
				callId: vm.chatId,
				userId: vm.user.id,
				queryEndTime: vm.queryStartTime,
				sortField: 'sendTime',
				sortOrder: 'desc',
				pageSize: 10,
			}).then(function (res) {
				console.log(res)
				if (res.successful) {
					if (res.data.length > 0) {
						vm.queryStartTime = res.data[0].queryStartTimeString;
						vm.queryEndTime = res.data[0].queryEndTimeString;
						var msgs = reverseFilter(res.data);
						vm.msgs = msgs.concat(vm.msgs);
					}
				}
			}).finally(function () {
				$scope.$broadcast('scroll.refreshComplete');
			})
		};
		function startInteval() {
			chatInterval.interval = setInterval(function () {
				if (!vm.call || vm.call.state == 2) {
					return;
				}
				xhr.get('HealthInquiry/com/callMsg/callMsgs', {
					callId: vm.chatId,
					userId: vm.user.id,
					queryStartTime: vm.queryEndTime,
					sortField: 'sendTime',
					sortOrder: 'desc',
					pageSize: 10,
				}, true).then(function (res) {
					if (res.successful) {
						for (var i = 0; i < res.data.length; i++) {
							var check = true;
							for (var j = 0; j < vm.msgs.length; j++) {
								if (vm.msgs[j].id == res.data[i].id) {
									check = false;
									break;
								}
							}
							if(check){
								vm.msgs.push(res.data[i]);
								messageToBottom();
							}
						}
					}
				}, function (error) {
					clearInterval(chatInterval.interval);
					popup.confirm('加载失败'+error+'?', '重新加载', '返回').then(function (ok) {
						if (ok) {
							startInteval();
						} else {
							$ionicHistory.goBack();
						}
					});
				})
			}, 1000)
		}
		startInteval();
		
		var ispost = false;
		vm.sendMsg = function (userId, message, msgType) {
			if (!vm.message || ispost) {
				return;
			}
			ispost = true;
			xhr.get('HealthInquiry/com/callMsg/sendMsg', {
				callId: vm.chatId,
				userId: userId || vm.user.id,
				content: message || vm.message,
				msgType: msgType || 0
			}).then(function (res) {
				vm.msgs.push(res.data);
				vm.message = "";
				messageToBottom();
			}).finally(function () {
				ispost = false;
			});
		};
		vm.getImage = function () {
			Cameranav.getPicture(function(imgUri) {
                $ionicLoading.show({
                    template: '正在上传…'
                });
                fileTransfer.upload(imgUri, vm.user.id, function(res) {
                	$ionicLoading.hide();
                    if (res.successful) {
                    	vm.message = "  ";
                    	vm.sendMsg(vm.user.id, res.data.picUrl, 1);
					}
                });
            })
		}
		vm.keyup = function ($event) {
			if ($event.keyCode == 13) {
				vm.sendMsg(vm.user.id, vm.message);
			}
		};
		function messageToBottom() {
            $timeout(function () {
                $anchorScroll("msg-bottom", 0);
            }, 0);
        };
		(function (startCall) {
			startCall().then(function () {
				vm.loadMsg().then(function (res) {
					messageToBottom();
				});
			});
		})(function () {
			var defer = $q.defer();
			if ($stateParams.docId) {
				xhr.get('HealthInquiry/com/call/startCall', {
					fromUser: vm.user.id,
					toUser: $stateParams.docId
				}).then(function (res) {
					if (res.successful) {
						vm.call = res.data;
						vm.chatId = res.data.id;
						vm.topTitle = res.resultMsg;
					}
					defer.resolve(res);
				}, function (err) {
					defer.reject();
					$ionicHistory.goBack();
				});
			} else {
				vm.chatId = $stateParams.chatId;
				vm.call = {
					chatId: $stateParams.chatId,
					state: $stateParams.state
				};
				defer.resolve();
			}
			return defer.promise;
			
		});
	}
})();
(function () {
	angular
	.module('ydApp.chat')
	.config(function ($stateProvider) {
		$stateProvider.state('post-chat', {
			cache: false,
			url: '/post-chat',
			controller: "postChatCtrl",
			templateUrl: 'views/chats/post-chat.html'
		});
		
	})
	.controller("postChatCtrl", postChatCtrl);

	function postChatCtrl ($scope, xhr, localStore, reverseFilter, $timeout, $anchorScroll, chatInterval) {
		var vm = $scope.vm = {};
		vm.chatId = '';
		vm.user = localStore.get('user');
		vm.queryStartTime = "";
		vm.queryEndTime = "";
		vm.msgs = [];
		vm.loadMsg = function() {
			return xhr.get('HealthInquiry/com/callMsg/callMsgs', {
				callId: vm.chatId,
				userId: vm.user.id,
				queryEndTime: vm.queryStartTime,
				sortField: 'sendTime',
				sortOrder: 'desc',
				pageSize: 10,
			}).then(function (res) {
				if (res.successful) {
					if (res.data.length > 0) {
						vm.queryStartTime = res.data[0].queryStartTimeString;
						vm.queryEndTime = res.data[0].queryEndTimeString;
						var msgs = reverseFilter(res.data);
						vm.msgs = msgs.concat(vm.msgs);
					}
					if (vm.msgs.length == 0) {
						vm.message = "  ";
						vm.sendMsg(0, '请详细描述您的症状、疾病和身体情况，延陵医道会为您提供相关帮助');
					}
				}
			}).finally(function () {
				$scope.$broadcast('scroll.refreshComplete');
			})
		};
		function startInteval() {
			chatInterval.interval = setInterval(function () {
				xhr.get('HealthInquiry/com/callMsg/callMsgs', {
					callId: vm.chatId,
					userId: vm.user.id,
					queryStartTime: vm.queryEndTime,
					sortField: 'sendTime',
					sortOrder: 'desc',
					pageSize: 10,
				}).then(function (res) {
					if (res.successful) {
						for (var i = 0; i < res.data.length; i++) {
							var check = true;
							for (var j = 0; j < vm.msgs.length; j++) {
								if (vm.msgs[j].id == res.data[i].id) {
									check = false;
									break;
								}
							}
							if(check){
								vm.msgs.push(res.data[i]);
								messageToBottom();
							}
						}
					}
				}, function (error) {
					clearInterval(chatInterval.interval);
					popup.confirm('加载失败'+error+'?', '重新加载', '返回').then(function (ok) {
						if (ok) {
							startInteval();
						} else {
							$ionicHistory.goBack();
						}
					});
				})
			}, 1000)
		}
		startInteval();
		var ispost = false;
		vm.sendMsg = function (userId, message) {
			if (!vm.message || ispost) {
				return;
			}
			ispost = true;
			xhr.get('HealthInquiry/com/callMsg/sendMsg', {
				callId: vm.chatId,
				userId: userId || vm.user.id,
				content: message || vm.message,
				msgType: 0
			}).then(function (res) {
				vm.msgs.push(res.data);
				vm.message = "";
				messageToBottom();
			}).finally(function () {
				ispost = false;
			});
		};
		vm.keyup = function ($event) {
			if ($event.keyCode == 13) {
				vm.sendMsg(vm.user.id, vm.message);
			}
		}
		function messageToBottom() {
            $timeout(function () {
                $anchorScroll("msg-bottom", 0);
            }, 0);
        }
		(function (startCall) {
			startCall().then(function () {
				vm.loadMsg().then(function () {
					messageToBottom();
				});
			});
		})(function () {
			return xhr.get('HealthInquiry/com/call/startDutyCall', {
				fromUser: vm.user.id
			}).then(function (res) {
				if (res.successful) {
					vm.chatId = res.data.id;
					vm.docHead = res.data.toUserHeadImgUrl;
					vm.head = res.data.fromUserHeadImgUrl;
					vm.topTitle = res.resultMsg;
				}
			});
		});

		
	}
})();
(function() {
	angular
		.module('ydApp.chat')
		.config(function($stateProvider) {
			$stateProvider.state('tabs.recent-chat', {
				url: '/recent-chat',
				nativeTransitions: null,
				views: {
					'recent-chat-tab': {
						controller: "recentChatCtrl",
						templateUrl: 'views/chats/recent-chat.html'
					}
				}
			});
			$stateProvider.state('tabs.recent-chat-doc', {
				url: '/recent-chat-doc',
				nativeTransitions: null,
				views: {
					'recent-chat-tab': {
						controller: "recentChatCtrl",
						templateUrl: 'views/chats/recent-chat.html'
					}
				}
			});
		})
		.controller("recentChatCtrl", recentChatCtrl)
		.controller("recentChatDocCtrl", recentChatDocCtrl);

	function recentChatCtrl($scope, xhr, $state, localStore) {

		var vm = $scope.vm = {};

		$scope.downloadImg = function(img) {
			return config.api + "HealthInquiry" + img;
		}

		var user = localStore.get("user");

		var userType = localStore.get("userType");

		if (userType == 2) {
			vm.condition = {
				pageIndex: -1,
				//toUser: 1111
				toUser: user.id
			}

			vm.tabList = [];
			$scope.toChat = function(item) {
				$state.go('chat', {
					chatId: item.id,
					state: item.state,
					docHead: item.toUserHeadImgUrl,
					head: item.fromUserHeadImgUrl
				});
			}
			vm.search = function() {
				xhr.get('HealthInquiry/com/call/findByDoctorCondition', vm.condition).then(function(result) {
					vm.tabList = result.data;
				})
			};

			vm.doRefresh = function() {
				vm.tabList = [];
				vm.condition.pageIndex = 0;
				vm.nodata = false;
				vm.load().finally(function() {
					$scope.$broadcast('scroll.refreshComplete');
				});
			}
			vm.loadMore = function() {
				vm.condition.pageIndex++;
				vm.load().then(function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
				});
			}

			vm.load = function() {
				return xhr.get("HealthInquiry/com/call/findByDoctorCondition", vm.condition).then(function(result) {
					if (result.data.length == 0) {
						vm.nodata = true;
					}
					vm.tabList = vm.tabList.concat(result.data);
				})
			}
			$scope.delete = function (item) {
				xhr.get("HealthInquiry/com/call/deleteByDoctor", {
					id: item.id,
					toUser: item.toUser
				}).then(function(result) {
					for (var i = 0; i < vm.tabList.length; i++) {
						if (vm.tabList[i] == item) {
							vm.tabList.splice(i, 1);
							break;
						}
					}
				});
			}
		} else {
			vm.condition = {
				pageIndex: -1,
				//fromUser: 'e3f7e6f0-d01d-4136-86dc-1158b7f4737d'
				fromUser: user.id
			}

			vm.tabList = [];
			$scope.toChat = function(item) {
				$state.go('chat', {
					chatId: item.id,
					state: item.state,
					docHead: item.toUserHeadImgUrl,
					head: item.fromUserHeadImgUrl
				});
			}
			vm.search = function() {
				xhr.get('HealthInquiry/com/call/findByUserCondition', vm.condition).then(function(result) {
					vm.tabList = result.data;
				})
			};

			vm.doRefresh = function() {
				vm.tabList = [];
				vm.condition.pageIndex = 0;
				vm.nodata = false;
				vm.load().finally(function() {
					$scope.$broadcast('scroll.refreshComplete');
				});
			}
			vm.loadMore = function() {
				vm.condition.pageIndex++;
				vm.load().then(function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
				});
			}

			vm.load = function() {
				return xhr.get("HealthInquiry/com/call/findByUserCondition", vm.condition).then(function(result) {
					if (result.data.length == 0) {
						vm.nodata = true;
					}
					vm.tabList = vm.tabList.concat(result.data);
				})
			}
			
			$scope.delete = function (item) {
				xhr.get("HealthInquiry/com/call/deleteByUser", {
					id: item.id,
					fromUser: item.fromUser
				}).then(function(result) {
					for (var i = 0; i < vm.tabList.length; i++) {
						if (vm.tabList[i] == item) {
							vm.tabList.splice(i, 1);
							break;
						}
					}
				});
			}
		}

	}

	function recentChatDocCtrl($scope, xhr, localStore, $state) {

		var vm = $scope.vm = {};

		$scope.downloadImg = function(img) {
			return config.api + "HealthInquiry" + img;
		}

		var user = localStore.get("user");

		vm.condition = {
			pageIndex: -1,
			//toUser: 1111
			toUser: user.id
		}

		vm.tabList = [];
		$scope.toChat = function(item) {
			$state.go('chat', {
				chatId: item.id,
				state: item.state,
				docHead: item.toUserHeadImgUrl,
				head: item.fromUserHeadImgUrl
			});
		}
		vm.search = function() {
			xhr.get('HealthInquiry/com/call/findByDoctorCondition', vm.condition).then(function(result) {
				vm.tabList = result.data;
			})
		};

		vm.doRefresh = function() {
			vm.tabList = [];
			vm.condition.pageIndex = 0;
			vm.nodata = false;
			vm.load().finally(function() {
				$scope.$broadcast('scroll.refreshComplete');
			});
		}
		vm.loadMore = function() {
			vm.condition.pageIndex++;
			vm.load().then(function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
			});
		}

		vm.load = function() {
			return xhr.get("HealthInquiry/com/call/findByDoctorCondition", vm.condition).then(function(result) {
				if (result.data.length == 0) {
					vm.nodata = true;
				}
				vm.tabList = vm.tabList.concat(result.data);
			})
		}
	}
})();
(function() {
	angular
		.module('ydApp.check', [])
		.config(function($stateProvider) {
			$stateProvider.state('add-check', {
				cache: false,
				url: '/add-check:id',
				controller: "addCheckCtrl",
				templateUrl: 'views/check/add-check.html'
			});
			$stateProvider.state('edit-check', {
				cache: false,
				url: '/edit-check:id',
				controller: "editCheckCtrl",
				templateUrl: 'views/check/edit-check.html'
			});
			$stateProvider.state('add-check-succ', {
				cache: false,
				url: '/add-check-succ',
				controller: "addCheckSuccCtrl",
				templateUrl: 'views/check/add-check-succ.html'
			});
		})
		.controller("addCheckCtrl", addCheckCtrl)
		.controller("editCheckCtrl", editCheckCtrl)
		.controller("addCheckSuccCtrl", addCheckSuccCtrl);

	function addCheckCtrl(xhr, $scope, $state, $window, localStore, $ionicLoading, Cameranav, fileTransfer, popup, $stateParams, $ionicModal) {

		var vm = $scope.vm = {};

		$scope.downloadImg = function(img) {
			return config.api + "HealthInquiry" + img;
		}

		vm.model = {};
		vm.ipData = {}
		$scope.showImages = function(index) {
			vm.ipData.showImage(index);
		}

		var user = localStore.get("user");

		vm.model.userId = user.id;

		var addcheck = localStore.get("addcheck");

		if (addcheck) {
			vm.model = addcheck;
		}

		if ($stateParams.id) {
			vm.isDetail = true;
			vm.title = "体检鉴定详情";
		} else {
			vm.title = "新增体检鉴定";
		}

		if (user.branchId) {
			vm.model.branchId = user.branchId;
			vm.model.branchName = user.branchName;
		} else {
			vm.model.branchName = "选择科室";
		}

		if (!$stateParams.id) {
			if (user.docId) {
				vm.model.doctorUserId = user.docId;
				vm.model.doctorName = user.docName;
				xhr.get('HealthInquiry/com/appraisal/selectCallCost', {
					id: user.docId
				}).then(function(result) {
					vm.model.apprCost = result.data.appraisalCost;
				});
			} else {
				vm.model.doctorName = "选择医生";
			}
		}

		if (vm.isDetail) {
			xhr.get('HealthInquiry/com/appraisal/findById', {
				id: $stateParams.id
			}).then(function(result) {
				vm.model = result.data;
				vm.ipData.images = vm.model.appraisalPictures;
				// var pisc = result.data.appraisalPictures[0].split(',');
				// result.data.appraisalPictures = pisc;
				// vm.model = result.data;
				vm.imgWidth = vm.model.appraisalPictures.length * 64;
				// console.log(JSON.stringify(vm.model))
			});
		}
		vm.select = function(params) {
			if (vm.isDetail) {
				return;
			}

			var user = localStore.save("addcheck", vm.model);

			$state.go(params, {
				state: 'add-check',
				branchId: localStore.get("user").branchId
			});
		}

		vm.submit = function() {
			if (vm.model.appraisalPictures.length == 0) {
				popup.alert('请选择图片');
				return;
			}
			// var pics = '';
			// for (var i = 0; i < vm.model.appraisalPictures.length; i++) {
			// 	pics+= 'appraisalPictures='+vm.model.appraisalPictures[i]+'&';
			// }
			// vm.model.appraisalPictures = undefined;
			// vm.model.appraisalPictures = pics;
			// console.log(JSON.stringify(vm.model))
			xhr.post('HealthInquiry/com/appraisal/saveOrUpdateJson', vm.model).then(function(result) {
				localStore.del('addcheck');
				$state.go('add-check-succ');
			}, function(err) {
				console.log(JSON.stringify(err))
			});
		}

		$scope.getAvatar = function() {
			if (vm.isDetail || vm.model.appraisalPictures.length >= 10) {
				return;
			}
			Cameranav.getPicture(function(imgUri) {
					$ionicLoading.show({
						template: '正在上传…'
					});
					fileTransfer.upload(imgUri, user.id, function(res) {
						$ionicLoading.hide();
						if (res.successful) {
							vm.model.appraisalPictures.push(res.data.picUrl);
							vm.ipData.images = vm.model.appraisalPictures;
							vm.imgWidth = vm.model.appraisalPictures.length * 64;
						}
					});
				})
				//这里为图片上传成功后服务器返回的url
		}

		$scope.delAvatar = function(index) {
			if (vm.isDetail) {
				return;
			}
			//长按删除图片
			vm.model.appraisalPictures.splice(index, 1);
			vm.ipData.images = vm.model.appraisalPictures;
			vm.imgWidth = vm.model.appraisalPictures.length * 64;
		}

		vm.imgWidth = 0;
		//vm.model.appraisalPictures = ['img/temp1.jpg', 'img/temp1.jpg', 'img/temp1.jpg', 'img/temp1.jpg', 'img/temp1.jpg', 'img/temp1.jpg']
		vm.model.appraisalPictures = [];
		vm.imgWidth = vm.model.appraisalPictures.length * 64;

	}

	function editCheckCtrl(xhr, $scope, $state, $window, localStore, $ionicLoading, Cameranav, fileTransfer, popup, $stateParams) {

		var vm = $scope.vm = {};

		$scope.downloadImg = function(img) {
			return config.api + "HealthInquiry" + img;
		}

		var editcheck = localStore.get("editcheck");

		var user = localStore.get("user");

		vm.model = {};
		vm.ipData = {}
		$scope.showImages = function(index) {
			vm.ipData.showImage(index);
		}

		if (editcheck && editcheck.apprState == 0 && user.branchId) {
			editcheck.branchId = user.branchId;
			xhr.get('HealthInquiry/com/appraisal/refuseAppraisal', editcheck).then(function(result) {
				popup.alert(result.resultMsg);
				localStore.del("editcheck");
				$window.history.back();
				//$state.go('tabs.recent-check');
				return;
			});
		}

		xhr.get('HealthInquiry/com/appraisal/findById', {
			id: $stateParams.id
		}).then(function(result) {
			vm.model = result.data;
			vm.ipData.images = vm.model.appraisalPictures;
			//vm.model.appraisalPictures[0].
			//alert(typeof(vm.model.appraisalPictures[0]))
			// console.log(JSON.stringify(result.data))
			localStore.del("editcheck");
			vm.imgWidth = vm.model.appraisalPictures.length * 64;
		});

		vm.submit = function() {
			xhr.get('HealthInquiry/com/appraisal/doAppraisal', vm.model).then(function(result) {
				//$state.go('tabs.recent-check');
				$window.history.back();
			});
		}

		// vm.notidentify = function() {
		// 	localStore.save("editcheck", vm.model);
		// 	$state.go('register-doc-info-depart', {
		// 		state: 'edit-check'
		// 	});
		// };

		vm.notidentify = function() {
			popup.confirm('此报告是否无法鉴定,推荐其他科室?').then(function(res) {
				if (res) {
					localStore.save("editcheck", vm.model);
					$state.go('register-doc-info-depart', {
						state: 'edit-check'
					});
				}
			});
		}

		vm.imgWidth = 0;
		// vm.model.appraisalPictures = ['img/temp1.jpg', 'img/temp1.jpg', 'img/temp1.jpg', 'img/temp1.jpg', 'img/temp1.jpg', 'img/temp1.jpg']
		// vm.imgWidth = vm.model.appraisalPictures.length * 64;
	}

	function addCheckSuccCtrl($state, $timeout, $window) {
		$timeout(function() {
			$window.history.go(-2);
			//$state.go('tabs.recent-check');
		}, 2000)
	}
})();
(function() {
	angular
		.module('ydApp.check')
		.config(function($stateProvider) {
			$stateProvider.state('tabs.recent-check', {
				url: '/recent-check',
				nativeTransitions: null,
				cache:false,
				views: {
					'recent-check-tab': {
						controller: "recentCheckCtrl",
						templateUrl: 'views/check/recent-check.html'
					}
				}
			});
			$stateProvider.state('tabs.recent-check-doc', {
				url: '/recent-check-doc-tab',
				nativeTransitions: null,
				views: {
					'recent-check-tab': {
						controller: "recentCheckCtrl",
						templateUrl: 'views/check/recent-check.html'
					}
				}
			});
		})
		.controller("recentCheckCtrl", recentCheckCtrl);

	function recentCheckCtrl($scope, xhr, localStore, $state) {
		localStore.del("editcheck");
		localStore.del('addcheck');

		var vm = $scope.vm = {};

		var userType = localStore.get("userType");

		if (userType == 2) {
			vm.user = localStore.get("user");
			vm.user.branchId = null;
			//0526新加
			vm.user.docId= null;
			//0526新加
			localStore.save("user", vm.user);

			vm.condition = {
				pageIndex: -1,
				sortField: 'createTime',
				sortOrder: 'desc',
				doctorUserId: vm.user.id
			}

			vm.data = [];
			vm.nodata = false;

			vm.search = function() {
				xhr.get('HealthInquiry/com/appraisal/findByCondition', vm.condition).then(function(result) {
					vm.data = result.data;
				});
			};

			vm.doRefresh = function() {
				vm.data = [];
				vm.condition.pageIndex = 0;
				vm.nodata = false;
				vm.load().finally(function() {
					$scope.$broadcast('scroll.refreshComplete');
				});
			}
			vm.loadMore = function() {
				vm.condition.pageIndex++;
				vm.load().then(function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
				});
			}

			vm.load = function() {
				return xhr.get("HealthInquiry/com/appraisal/findByCondition", vm.condition).then(function(result) {
					if (result.data.length == 0) {
						vm.nodata = true;
					}
					vm.data = vm.data.concat(result.data);
				})
			}

			vm.create = function() {
				$state.go("add-check");
			}

			vm.detail = function(id) {
				$state.go("edit-check", {
					id: id
				});
			}
			$scope.delete = function (item) {
				xhr.get("HealthInquiry/com/appraisal/deleteByDoctor", {
					id: item.id,
					doctorUserId: item.doctorUserId
				}).then(function(result) {
					for (var i = 0; i < vm.data.length; i++) {
						if (vm.data[i] == item) {
							vm.data.splice(i, 1);
							break;
						}
					}
				});
			}
		} else {
			vm.user = localStore.get("user");
			vm.user.branchId = null;
			//0526新加
			vm.user.docId= null;
			//0526新加
			localStore.save("user", vm.user);

			vm.condition = {
				pageIndex: -1,
				sortField: 'createTime',
				sortOrder: 'desc',
				userId: vm.user.id
			}

			vm.data = [];
			vm.nodata = false;

			vm.search = function() {
				xhr.get('HealthInquiry/com/appraisal/findByCondition', vm.condition).then(function(result) {
					vm.data = result.data;
				});
			};

			vm.doRefresh = function() {
				vm.data = [];
				vm.condition.pageIndex = 0;
				vm.nodata = false;
				vm.load().finally(function() {
					$scope.$broadcast('scroll.refreshComplete');
				});
			}
			vm.loadMore = function() {
				vm.condition.pageIndex++;
				vm.load().then(function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
				});
			}

			vm.load = function() {
				return xhr.get("HealthInquiry/com/appraisal/findByCondition", vm.condition).then(function(result) {
					if (result.data.length == 0) {
						vm.nodata = true;
					}
					vm.data = vm.data.concat(result.data);
				})
			}

			vm.create = function() {
				$state.go("add-check");
			}

			vm.detail = function(id) {
				$state.go("add-check", {
					id: id
				});
			}
			$scope.delete = function (item) {
				xhr.get("HealthInquiry/com/appraisal/deleteByUser", {
					id: item.id,
					userId: item.userId
				}).then(function(result) {
					for (var i = 0; i < vm.data.length; i++) {
						if (vm.data[i] == item) {
							vm.data.splice(i, 1);
							break;
						}
					}
				});
			}
		}



	}
})();
(function() {
	angular
		.module('ydApp.classRoom', [])
		.config(function($stateProvider) {
			$stateProvider.state('classRoom-list', {
				url: '/classRoom-list',
				controller: "classRoomListCtrl",
				templateUrl: 'views/classRoom/classRoom-list.html'
			});
		})
		.controller("classRoomListCtrl", classRoomListCtrl);

	function classRoomListCtrl($scope, xhr, $state, $location, $cordovaInAppBrowser) {
		var vm = $scope.vm = {};

		$scope.downloadImg = function(img) {
			return config.api + "HealthInquiry" + img;
		}

		vm.condition = {
			pageIndex: 0,
			pageSize: 10000
		}

		xhr.get("HealthInquiry/com/lecture/findByCondition", vm.condition).then(function(result) {
			vm.data = result.data;
		})

		vm.toDetail = function(url) {
			$location.url(url);
		}

		var options = {
			location: 'no',
			clearcache: 'no',
			toolbar: 'yes'
		};

		$scope.open = function(link) {
			//http://115.28.128.133:8080/HealthInquiry/view/base/sendMsg_form.jsp
			$cordovaInAppBrowser.open(link, '_blank', options);
		}
	}
})();
(function() {
	angular
		.module('ydApp.clinic', [])
		.config(function($stateProvider) {
			$stateProvider.state('add-clinic', {
				cache: false,
				url: '/add-clinic',
				controller: "addClinicCtrl",
				templateUrl: 'views/clinic/add-clinic.html'
			});
			$stateProvider.state('add-clinic-succ', {
				cache: false,
				url: '/add-clinic-succ',
				controller: "addClinicSuccCtrl",
				templateUrl: 'views/clinic/add-clinic-succ.html'
			});
			$stateProvider.state('del-clinic', {
				url: '/del-clinic:id',
				controller: "delClinicCtrl",
				templateUrl: 'views/clinic/del-clinic.html'
			});
		})
		.controller("addClinicCtrl", addClinicCtrl)
		.controller("addClinicSuccCtrl", addClinicSuccCtrl)
		.controller("delClinicCtrl", delClinicCtrl);

	function addClinicCtrl($scope, $state, localStore, xhr, popup, bdCalendar) {
		var vm = $scope.vm = {};

		vm.createmodel = {};

		$scope.$watch('vm.date', function() {
			for (var i = 0; i < vm.list.length; i++) {
				if ((new Date(vm.date).toLocaleDateString()) == (new Date(vm.list[i]).toLocaleDateString())) {
					vm.add = false;
					$state.go('del-clinic', {
						id: vm.model[i].id
					});
					return;
				}
			}
			vm.add = true;
			vm.createmodel.startTimeString = vm.date + ' 00:00:01';
			vm.createmodel.endTimeString = vm.date + ' 23:59:59';
		})

		vm.list = [];

		var user = localStore.get("user");

		vm.createmodel.doctorId = user.id;

		xhr.get("HealthInquiry/com/clinic/findByDoctorId", {
			doctorId: user.id
		}).then(function(result) {
			vm.model = result.data;
			for (var i = 0; i < vm.model.length; i++) {
				vm.list.push(vm.model[i].startTime)
			}
		})

		vm.limit = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

		vm.submit = function() {
			xhr.get("HealthInquiry/com/clinic/saveOrUpdate", vm.createmodel).then(function(result) {
				$state.go('add-clinic-succ');
			})
		};
	}

	function addClinicSuccCtrl($state, $timeout) {
		$timeout(function() {
			$state.go('add-clinic');
		}, 2000)
	}

	function delClinicCtrl($state, $scope, $timeout, xhr, localStore, $stateParams) {
		var vm = $scope.vm = {};

		vm.user = localStore.get("user");

		xhr.get("HealthInquiry/com/clinic/findById", {
			id: $stateParams.id
		}).then(function(result) {
			vm.model = result.data;
		})

		vm.submit = function() {
			xhr.get("HealthInquiry/com/clinic/deleteByDoctorId", {
				id: $stateParams.id,
				doctorId: vm.user.id
			}).then(function(result) {
				$state.go('add-clinic-succ');
			})
		};
	}
})();
(function() {
	angular
		.module('ydApp.clinic')
		.config(function($stateProvider) {
			$stateProvider.state('clinic-list', {
				url: '/clinic-list',
				controller: "clinicListCtrl",
				templateUrl: 'views/clinic/clinic-list.html'
			});
			$stateProvider.state('clinic-detail', {
				url: '/clinic-detail',
				controller: "clinicDetailCtrl",
				templateUrl: 'views/clinic/clinic-detail.html'
			});
		})
		.controller("clinicListCtrl", clinicListCtrl)
		.controller("clinicDetailCtrl", clinicDetailCtrl);

	function clinicListCtrl($scope, xhr, $state) {
		var vm = $scope.vm = {};

		$scope.downloadImg = function(img) {
            return config.api + "HealthInquiry" + img;
        }

		vm.condition = {
			pageIndex: -1,
			sorter: 'intelligent',
			branchId: null
		}

		vm.search = function() {
			xhr.get('HealthInquiry/com/clinic/findByNow', vm.condition).then(function(result) {
				vm.data = result.data;
			});
		};

		xhr.get("HealthInquiry/com/branch/findByCondition", {
			pageIndex: 0,
			pageSize: 100
		}).then(function(res) {
			if (res.successful) {
				vm.departs = res.data;
			}
		})

		vm.departSearch = function(branchId) {
			if (branchId) {
				vm.condition.branchId = branchId;
			} else {
				vm.condition.branchId = null;
			}

			vm.menu(1);
			vm.doRefresh();
		}

		vm.sortSearch = function(sorter) {
			vm.condition.sorter = sorter;
			vm.menu(2);
			vm.doRefresh();
		}

		// vm.search();

		vm.flag = 0;
		vm.data = [];

		vm.menu = function(id) {
			if (vm.flag == id) {
				vm.flag = 0;
			} else {
				vm.flag = id;
			}
		}

		vm.doRefresh = function() {
			vm.data = [];
			vm.condition.pageIndex = 0;
			vm.nodata = false;
			vm.load().finally(function() {
				$scope.$broadcast('scroll.refreshComplete');
			});
		}
		vm.loadMore = function() {
			vm.condition.pageIndex++;
			vm.load().then(function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
			});
		}
		vm.load = function() {
			return xhr.get("HealthInquiry/com/clinic/findByNow", vm.condition).then(function(result) {
				if (result.data.length == 0) {
					vm.nodata = true;
				}
				vm.data = vm.data.concat(result.data);
			})
		}
		vm.toDetail = function(docId) {
			$state.go("doc-detail", {
				docId: docId
			});
		}
	}

	function clinicDetailCtrl($scope) {
		var vm = $scope.vm = {};
	}
})();
(function () {
	angular
	.module('ydApp.doc', [])
	.config(function ($stateProvider) {
		$stateProvider.state('doc-detail', {
			url: '/doc-detail/:docId',
			controller: "docDetailCtrl",
			templateUrl: 'views/docs/doc-detail.html'
		});
	})
	.controller("docDetailCtrl", docDetailCtrl);

	function docDetailCtrl ($scope, $stateParams, xhr, $state, popup) {
		var vm = $scope.vm = {};
		xhr.get("HealthInquiry/com/doctor/findById", {
			id: $stateParams.docId
		}).then(function (res) {
			vm.doc = res.data;
			console.log(res)
		});

		vm.toChat = function () {
			if (vm.doc.isOnline == 1) {
				$state.go('chat', {
					docId: $stateParams.docId,
					docHead: vm.doc.headImgUrl
				})
			}
		}
		vm.toGood = function (argument) {
			$state.go('doc-good', {
				docId: $stateParams.docId
			})
		}
	}
})();
(function () {
	angular
	.module('ydApp.doc')
	.config(function ($stateProvider) {
		$stateProvider.state('doc-good', {
			url: '/doc-good/:docId',
			controller: "docGoodCtrl",
			templateUrl: 'views/docs/doc-good.html'
		});
		$stateProvider.state('doc-good-succ', {
			url: '/doc-good-succ',
			templateUrl: 'views/docs/doc-good-succ.html'
		});
	})
	.controller("docGoodCtrl", docGoodCtrl);

	function docGoodCtrl ($scope, xhr, $stateParams, popup, localStore, $ionicLoading) {
		var vm = $scope.vm = {};
		var user = localStore.get("user");
		xhr.get("HealthInquiry/com/doctor/findById", {
			id: $stateParams.docId
		}).then(function (res) {
			vm.doc = res.data;
		});
		vm.costMoney = 10;
		vm.selectCost = function (moeny) {
			vm.costMoney = moeny;
		}
		vm.save = function (){
			// if (!vm.content) {
			// 	popup.alert('请选择图片');
			// 	return;
			// }
			$ionicLoading.show({
				template: '正在提交…'
			});
			xhr.get("HealthInquiry/com/doctorPraise/saveOrUpdate", {
				userId: user.id,
				doctorId: $stateParams.docId,
				praiseCost: vm.costMoney,
				content: vm.content
			}).then(function (res) {
				$ionicLoading.hide();
				popup.alert('提交成功');
				vm.data = [];
				vm.condition.pageIndex = 0;
				vm.load();
			});
		};

		vm.data = [];
		vm.nodata = false;
		vm.condition = {
			pageIndex: -1,
			sortField: 'modifyTime',
			sortOrder: 'desc',
			doctorId: $stateParams.docId
		}
		vm.loadMore = function() {
			vm.condition.pageIndex++;
			vm.load().then(function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
			});
		}
		vm.load = function() {
			return xhr.get("HealthInquiry/com/doctorPraise/findByDoctorId", vm.condition).then(function(result) {
				if (result.data.length == 0) {
					vm.nodata = true;
				}
				vm.data = vm.data.concat(result.data);
			})
		}
	}
})();
(function() {
	angular
		.module('ydApp.doc')
		.config(function($stateProvider) {
			$stateProvider.state('doc-list', {
				url: '/doc-list?keyword?branchId?state',
				controller: "docListCtrl",
				templateUrl: 'views/docs/doc-list.html'
			});
			$stateProvider.state('doc-listselect', {
				url: '/doc-listselect/?state/?branchId',
				controller: "docListSelectCtrl",
				templateUrl: 'views/docs/doc-list.html'
			});
		})
		.controller("docListCtrl", docListCtrl)
		.controller("docListSelectCtrl", docListSelectCtrl);

	function docListCtrl($scope, xhr, $stateParams, $state, localStore) {
		var vm = $scope.vm = {};
		vm.user = localStore.get("user");
		vm.flag = 0;
		vm.conditions = {
			pageIndex: -1,
			condition: "",
			branchId: "",
			sorter: "intelligent",
			userId: vm.user.id
		};

		if ($stateParams.state == 'add-check') {
			vm.conditions.auditState = 0;
		}

		vm.conditions.branchId = $stateParams.branchId;
		vm.conditions.condition = $stateParams.keyword;

		vm.menu = function(id) {
			if (vm.flag == id) {
				vm.flag = 0;
			} else {
				vm.flag = id;
			}
		}
		vm.departSearch = function(branchId) {
			vm.conditions.branchId = branchId || undefined;
			vm.flag = 0;
			vm.doRefresh();
		}
		vm.sort = function(name, desc) {
			vm.conditions.sorter = name;
			vm.flag = 0;
			vm.doRefresh();
		}
		vm.keywordSearch = function(event) {
			if (event.keyCode == 13) {
				vm.doRefresh();
			}
		};
		xhr.get("HealthInquiry/com/branch/findByCondition", {
			pageIndex: 0,
			pageSize: 100
		}).then(function(res) {
			if (res.successful) {
				vm.departs = res.data;
			}
		})
		vm.docs = [];
		vm.nodata = false;

		vm.doRefresh = function() {
			vm.docs = [];
			vm.conditions.pageIndex = 0;
			vm.nodata = false;
			vm.load().finally(function() {
				$scope.$broadcast('scroll.refreshComplete');
			});
		}
		vm.loadMore = function() {
			vm.conditions.pageIndex++;
			vm.load().then(function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
			});
		}
		vm.load = function() {
			return xhr.get("HealthInquiry/com/doctor/queryDoctor", vm.conditions).then(function(docs) {
				if (docs.data.length == 0) {
					vm.nodata = true;
				}
				vm.docs = vm.docs.concat(docs.data);
			})
		}
		vm.toDetail = function(docId, docName) {
			var state = $stateParams.state;
			if (state) {
				var user = localStore.get("user");
				user.docName = docName;
				user.docId = docId;
				localStore.save("user", user);
				$state.go(state);
			} else {
				$state.go("doc-detail", {
					docId: docId
				});
			}

		}
	}

	function docListSelectCtrl($window, $scope, xhr, $stateParams, $state, localStore) {
		var vm = $scope.vm = {};
		vm.user = localStore.get("user");
		vm.flag = 0;
		vm.conditions = {
			pageIndex: -1,
			auditState: 1,
			appraisalState: 1,
			branchId: 0,
			pageSize: 50,
			sorter: ""
		};

		vm.conditions.branchId = $stateParams.branchId;
		vm.conditions.condition = $stateParams.keyword;

		vm.menu = function(id) {
			if (vm.flag == id) {
				vm.flag = 0;
			} else {
				vm.flag = id;
			}
		}
		vm.departSearch = function(branchId) {
			vm.conditions.branchId = branchId || undefined;
			vm.flag = 0;
			vm.doRefresh();
		}
		vm.sort = function(name, desc) {
			vm.conditions.sorter = name;
			if (name == 'intelligent') {
				vm.conditions.sorter = ''
			}
			vm.flag = 0;
			vm.doRefresh();
		}
		vm.keywordSearch = function(event) {
			if (event.keyCode == 13) {
				vm.doRefresh();
			}
		};
		xhr.get("HealthInquiry/com/branch/findByCondition", {
			pageIndex: 0,
			pageSize: 100
		}).then(function(res) {
			if (res.successful) {
				vm.departs = res.data;
			}
		})
		vm.docs = [];
		vm.nodata = false;

		vm.doRefresh = function() {
			vm.docs = [];
			vm.conditions.pageIndex = 0;
			vm.nodata = false;
			vm.load().finally(function() {
				$scope.$broadcast('scroll.refreshComplete');
			});
		}
		vm.loadMore = function() {
			vm.conditions.pageIndex++;
			vm.load().then(function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
			});
		}
		vm.load = function() {
			return xhr.get("HealthInquiry/com/doctor/findByCondition", vm.conditions).then(function(docs) {
				if (docs.data.length == 0) {
					vm.nodata = true;
				}
				vm.docs = vm.docs.concat(docs.data);
			})
		}
		vm.toDetail = function(docId, docName) {
			var state = $stateParams.state;
			if (state) {
				var user = localStore.get("user");
				user.docName = docName;
				user.docId = docId;
				localStore.save("user", user);
				if (angular.equals($stateParams.state, "add-check")) {
					$window.history.back();
				} else {
					$state.go(state);
				}
			} else {
				$state.go("doc-detail", {
					docId: docId
				});
			}

		}
	}
})();
(function () {
	angular
	.module('ydApp.doc')
	.config(function ($stateProvider) {
		$stateProvider.state('find-doc', {
			url: '/find-doc',
			controller: "findDocCtrl",
			templateUrl: 'views/docs/find-doc.html'
		});
	})
	.controller("findDocCtrl", findDocCtrl);

	function findDocCtrl ($scope, $state, xhr) {
		var vm = $scope.vm = {};
		vm.search = function (evt) {
			if (evt.keyCode == 13 && vm.keyword) {
				vm.toList({keyword: vm.keyword});
			}
		}
		vm.hotSearch = function (keyword) {
			vm.toList({keyword: keyword});
		}
		vm.departSearch = function (branchId) {
			vm.toList({branchId: branchId});
		}
		vm.toList = function (param) {
			$state.go("doc-list", param);
		}
		xhr.get("HealthInquiry/com/disease/findByCondition", {
			isCommon: 1,
			size: 12,
			sortField: 'orderNo'
		}).then(function (res) {
			if (res.successful) {
				vm.cyDeparts = res.data;
			}
		})
		xhr.get("HealthInquiry/com/branch/findByCondition", {
			pageIndex: 0,
			pageSize: 100
		}).then(function (res) {
			if (res.successful) {
				vm.departs = res.data;
			}
		})
	}
})();
(function() {
	angular
		.module('ydApp.health', [])
		.config(function($stateProvider) {
			$stateProvider.state('health-list', {
				url: '/health-list',
				controller: "healthListCtrl",
				templateUrl: 'views/health/health-list.html'
			});
		})
		.controller("healthListCtrl", healthListCtrl);

	function healthListCtrl($scope, xhr, $cordovaInAppBrowser, $location) {
		var vm = $scope.vm = {};

		$scope.downloadImg = function(img) {
			return config.api + "HealthInquiry" + img;
		}

		vm.condition = {
			pageIndex: -1
		}

		// xhr.get('HealthInquiry/com/article/findByCondition', vm.condition).then(function(result) {
		// 	vm.health = result.data;
		// })

		vm.nodata = false;
		vm.health = [];

		vm.doRefresh = function() {
			vm.health = [];
			vm.condition.pageIndex = 0;
			vm.nodata = false;
			vm.load().finally(function() {
				$scope.$broadcast('scroll.refreshComplete');
			});
		}
		vm.loadMore = function() {
			vm.condition.pageIndex++;
			vm.load().then(function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
			});
		}
		vm.load = function() {
			return xhr.get("HealthInquiry/com/article/findByCondition", vm.condition).then(function(result) {
				if (result.data.length == 0) {
					vm.nodata = true;
				}
				vm.health = vm.health.concat(result.data);
			})
		}
		vm.toDetail = function(url) {
			$location.url(url);
		}

		var options = {
			location: 'no',
			clearcache: 'no',
			toolbar: 'yes'
		};

		$scope.open = function(link) {
			$cordovaInAppBrowser.open(link, '_blank', options);
		}
	}
})();
(function() {
	angular
		.module('ydApp.home', [])
		.config(function($stateProvider) {
			$stateProvider.state('tabs.home', {
				// url: '/home',
				// cache: false,
				// controller: "homeCtrl",
				// templateUrl: 'views/home/home.html'
				url: '/home',
				nativeTransitions: null,
				views: {
					'home-tab': {
						controller: "homeCtrl",
						templateUrl: 'views/home/home.html'
					}
				}
			});
		})
		.controller("homeCtrl", homeCtrl);

	function homeCtrl($scope, $timeout, homeService, $rootScope, popup, $cordovaInAppBrowser, localStore, $location, $state, xhr, $ionicSideMenuDelegate) {
		var vm = $scope.vm = {};

		var user = localStore.get('user');

		vm.getMsgCount = function() {
			xhr.get('HealthInquiry/com/sysMessage/countUnreadByUserId', {
				userId: user.id
			}).then(function(result) {
				vm.count = result.data.count;
			})
		}

		vm.getMsgCount();

		$scope.toggleSlide = function() {
			vm.getMsgCount();
			getMessage();
			$scope.slideRight = !$scope.slideRight;
			vm.getMsgCount();
		}
		$scope.swipeLeft = function(e) {
			vm.getMsgCount();
			getMessage();
			$scope.slideRight = true;
		}
		$scope.swipeRight = function(e) {
			vm.getMsgCount();
			getMessage();
			$scope.slideRight = false;
		}

		//每分钟获取一次消息数目
		var getMsgCountEveryminute = function() {
			homeService.preventCycle = true;
			$timeout(function() {
				vm.getMsgCount();
				getMsgCountEveryminute();
			}, 60000)
		};

		if (!homeService.preventCycle) {
			getMsgCountEveryminute();
		}

		$scope.downloadImg = function(img) {
			return config.api + "HealthInquiry" + img;
		}

		$scope.search = function(event) {
			if (!vm.search) {
				return;
			}
			if (event.keyCode == 13) {
				$state.go('doc-list', {
					keyword: vm.search
				})
			}
		};
		xhr.get('HealthInquiry/com/advertising/findByPosition', {
			position: 1
		}).then(function(result) {
			vm.topBanners = result.data;
			//vm.banners = ['img/temp-banner.jpg'];
			for (var i = 0; i < vm.topBanners.length; i++) {
				vm.topBanners[i].imgUrl = $scope.downloadImg(vm.topBanners[i].imgUrl);
			}
			vm.topCarouselIndex = 0;
			if (vm.topBanners.length > 0) {
				var img = new Image();
				img.onload = function() {
					$scope.$apply(function() {
						var height = (window.screen.width / img.width) * img.height;
						vm.height = height;
					})
				}
				img.src = $scope.downloadImg(vm.topBanners[0].imgUrl);
			}
		})

		xhr.get('HealthInquiry/com/advertising/findByPosition', {
			position: 2
		}).then(function(result) {
			vm.middleBanners = result.data;
			//vm.banners = ['img/temp-banner.jpg'];
			for (var i = 0; i < vm.middleBanners.length; i++) {
				vm.middleBanners[i].imgUrl = $scope.downloadImg(vm.middleBanners[i].imgUrl);
			}
			vm.middleCarouselIndex = 0;
			if (vm.middleBanners.length > 0) {
				var img = new Image();
				img.onload = function() {
					$scope.$apply(function() {
						var height = (window.screen.width / img.width) * img.height;
						vm.height = height;
					})
				}
				img.src = vm.middleBanners[0].imgUrl;
			}
		})

		var getMessage = function() {
			return xhr.get('HealthInquiry/com/sysMessage/findByCondition', {
				userId: user.id
			}).then(function(result) {
				vm.message = result.data;
				for (var i = 0; i < vm.message.length; i++) {
					s1 = new Date(vm.message[i].sendTimeString.replace(/-/g, "/"));
					var now = new Date();
					s2 = new Date(now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 23:59:59');
					var days = s2.getTime() - s1.getTime();
					var time = parseInt(days / (1000 * 60 * 60 * 24));
					if (time == 0) {
						vm.message[i].day = "今天";
					} else if (time == 1) {
						vm.message[i].day = "昨天";
					} else {
						vm.message[i].day = "昨天之前";
					}
				}
			})
		};
		vm.doRefresh = function () {
			console.log('asd')
			getMessage().then(function () {
				vm.getMsgCount();
				$scope.$broadcast('scroll.refreshComplete');
			});
		}

		getMessage();

		xhr.get('HealthInquiry/com/article/findByCondition', {
			pageIndex: 0,
			pageSize: 5
		}).then(function(result) {
			vm.health = result.data;
		})

		vm.showMsg = function() {
			$ionicSideMenuDelegate.toggleRight();
		}
		vm.showSetting = function(argument) {
			vm.msgSetting = !vm.msgSetting;
		}
		vm.doRead = function() {
			xhr.get('HealthInquiry/com/sysMessage/readAll', {
				userId: user.id
			}).then(function() {
				popup.alert("标记成功！");
				vm.showSetting();
				vm.getMsgCount();
				getMessage();
			});
		}
		vm.deleteAll = function() {
			xhr.get('HealthInquiry/com/sysMessage/deleteAll', {
				userId: user.id
			}).then(function() {
				popup.alert("清除成功！");
				vm.getMsgCount();
				vm.showSetting();
				getMessage();
			});
		}

		var options = {
			location: 'no',
			clearcache: 'no',
			toolbar: 'yes'
		};

		$scope.open = function(link) {
			$cordovaInAppBrowser.open(link, '_blank', options);
		}

		$scope.showMessage = function(message) {
			xhr.get("HealthInquiry/com/sysMessage/readById", {
				msgId: message.id,
				userId: user.id
			}).then(function(result) {
				vm.count -= 1;
				message.state = 1;
				$state.go("messageDetail", {
					id: message.id,
					sendUserId: message.sendUserId,
					content: message.content,
					sendTimeString: message.sendTimeString
				})
			});
		}

	}
})();

(function() {
	'use strict';
	angular.module('ydApp.home').factory('homeService', [function() {
		return {
			preventCycle: false
		}
	}])
})();
(function() {
    angular
        .module('ydApp.login', [])
        .config(function($stateProvider) {
            $stateProvider.state('login', {
                url: '/login',
                cache: false,
                controller: "loginCtrl",
                templateUrl: 'views/login/login.html'
            });
            $stateProvider.state('loading', {
                url: '/loading',
                controller: "loadingCtrl",
                templateUrl: 'views/login/loading.html'
            });
        })
        .controller("loginCtrl", loginCtrl)
        .controller("loadingCtrl", loadingCtrl);


    function loginCtrl($scope, $state, xhr, localStore, popup, $ionicLoading) {
        var vm = $scope.vm = {};
        vm.user = {};

        vm.toHome = function() {
            $state.go('tabs.home')
        }

        vm.init = function() {
            var loginInfo = localStore.get("loginInfo");
            if (!angular.isUndefined(loginInfo) && loginInfo != null) {
                vm.user.code = loginInfo.code;
                vm.user.password = loginInfo.password;
                vm.remember = true;
            }
        }

        vm.init();

        vm.login = function() {
            $ionicLoading.show({
                template: '正在登陆'
            });
            if (vm.remember) {
                localStore.save("loginInfo", {
                    code: vm.user.code,
                    password: vm.user.password
                })
            } else {
                localStore.del("loginInfo");
            }
            xhr.get('HealthInquiry/com/login/app', vm.user).then(function(result) {
                var code=vm.user.code;
                var userInfoUrl = result.data.userType == 1 ? "HealthInquiry/com/user/findById" : "HealthInquiry/com/doctor/findById";
                xhr.get(userInfoUrl, {id:result.data.id}).then(function(data) {
                    vm.user=data.data;
                    vm.user.code=code;
                    vm.user.userType=result.data.userType;
                    console.log(vm.user)
                    localStore.save('user', vm.user);
                    localStore.save('userType', vm.user.userType);
                    $state.go('tabs.home');
                });
            });
        }


        vm.go = function(router) {
            $state.go(router);
        }
    }

    function loadingCtrl($scope, localStore, $state) {
        $scope.toHome = function() {
            localStore.save('isStart', true);
            $state.go('tabs.home')
        }
    }
})();

// (function() {
//     angular
//         .module('ydApp.user.info', [])
//         .config(function($stateProvider) {
//             $stateProvider.state('userInfo', {
//                 url: '/userInfo',
//                 cache: false,
//                 controller: 'userInfoCtrl',
//                 templateUrl: 'views/user/user-info.html'
//             });
//             $stateProvider.state('doctorInfo', {
//                 url: '/doctorInfo',
//                 cache: false,
//                 controller: 'userInfoCtrl',
//                 templateUrl: 'views/user/doctor-info.html'
//             });
//         })
//         .controller("userInfoCtrl", userInfoCtrl);

//     function userInfoCtrl($scope) {
//         var vm = $scope.vm = {};
//         vm.edit = true;
//     }
// })();
(function() {
    angular
        .module('ydApp.register', [])
        .config(function($stateProvider) {
            $stateProvider.state('register', {
                url: '/register',
                controller: "registerCtrl",
                templateUrl: 'views/user/register.html'
            });
            $stateProvider.state('register-user', {
                url: '/register-user',
                controller: "registerUserCtrl",
                templateUrl: 'views/user/register-user.html'
            });
            $stateProvider.state('register-doc', {
                url: '/register-doc',
                controller: "registerDocCtrl",
                templateUrl: 'views/user/register-doc.html'
            });
            $stateProvider.state('register-doc-info', {
                cache: false,
                url: '/register-doc-info',
                controller: "registerDocInfoCtrl",
                templateUrl: 'views/user/register-doc-info.html'
            });
            $stateProvider.state('register-doc-info-hospital', {
                url: '/register-doc-info-hospital:state',
                controller: "registerDocInfoHospitalCtrl",
                templateUrl: 'views/user/register-doc-info-hospital.html'
            });
            $stateProvider.state('register-doc-info-depart', {
                cache: false,
                url: '/register-doc-info-depart:state',
                controller: "registerDocInfoDepartCtrl",
                templateUrl: 'views/user/register-doc-info-depart.html'
            });
            $stateProvider.state('register-doc-info-depart2', {
                url: '/register-doc-info-depart2:state',
                controller: "registerDocInfoDepart2Ctrl",
                templateUrl: 'views/user/register-doc-info-depart2.html'
            });
            $stateProvider.state('register-doc-info-position', {
                url: '/register-doc-info-position:state',
                controller: "registerDocInfoPositionCtrl",
                templateUrl: 'views/user/register-doc-info-position.html'
            });
            $stateProvider.state('register-doc-info-succ', {
                url: '/register-doc-info-succ',
                controller: 'registerDocInfoSuccCtrl',
                templateUrl: 'views/user/register-doc-info-succ.html'
            });
            $stateProvider.state('register-noduty', {
                url: '/register-noduty',
                templateUrl: 'views/user/register-noduty.html'
            });
        })
        .controller("registerCtrl", registerCtrl)
        .controller("registerUserCtrl", registerUserCtrl)
        .controller("registerDocCtrl", registerDocCtrl)
        .controller("registerDocInfoCtrl", registerDocInfoCtrl)
        .controller("registerDocInfoHospitalCtrl", registerDocInfoHospitalCtrl)
        .controller("registerDocInfoDepartCtrl", registerDocInfoDepartCtrl)
        .controller("registerDocInfoDepart2Ctrl", registerDocInfoHospitalCtrl)
        .controller("registerDocInfoSuccCtrl", registerDocInfoSuccCtrl)
        .controller("registerDocInfoPositionCtrl", registerDocInfoPositionCtrl);

    function registerCtrl($scope, $state) {
        var vm = $scope.vm = {};
        vm.go = function(router) {
            $state.go(router);
        }
    }

    function registerUserCtrl($scope, $timeout, xhr, popup, $state) {
        var vm = $scope.vm = {};
        vm.user = {
            userType: 1
        };
        vm.enable = true;
        vm.getCode = function() {
            if (!vm.enable) {
                return;
            }
            if (vm.user.code) {
                xhr.get('HealthInquiry/com/sms/send', {
                    phone: vm.user.code
                }).then(function(result) {
                    vm.time = 60;
                    $scope.timeInteval();
                    vm.enable = false;
                });
            } else {
                popup.alert("请输入手机号码");
            }

        }

        $scope.timeInteval = function() {
            vm.time--;
            if (vm.time > 0) {
                $timeout($scope.timeInteval, 1000);
            } else {
                vm.enable = true;
            }
        }

        vm.register = function() {

            if (!vm.user.code) {
                popup.alert("请输入手机号码");
                return;
            }

            if (!vm.user.valiCode) {
                popup.alert("请输入验证码");
                return;
            }

            if (!vm.user.password) {
                popup.alert("请输入验密码");
                return;
            }
            if (!angular.equals(vm.user.password, vm.user.repassword)) {
                popup.alert("两次密码输入不一致");
                return;
            }
            if (!vm.agree) {
                popup.alert("您需要同意用户条款");
                return;
            }
            xhr.get('HealthInquiry/com/user/register', vm.user).then(function(result) {
                popup.alert(result.resultMsg);
                $state.go('login');
            });
        }

    }

    function registerDocCtrl($scope, $timeout, xhr, popup, $state, localStore) {
        var vm = $scope.vm = {};
        vm.enable = true;
        vm.user = {
            userType: 2
        };

        vm.getCode = function() {
            if (!vm.enable) {
                return;
            }
            if (vm.user.code) {
                xhr.get('HealthInquiry/com/sms/send', {
                    phone: vm.user.code
                }).then(function(result) {
                    vm.time = 60;
                    $scope.timeInteval();
                    vm.enable = false;
                });
            } else {
                popup.alert("请输入手机号码");
            }

        }

        $scope.timeInteval = function() {
            vm.time--;
            if (vm.time > 0) {
                $timeout($scope.timeInteval, 1000);
            } else {
                vm.enable = true;
            }
        }


        vm.register = function() {

            if (!vm.user.code) {
                popup.alert("请输入手机号码");
                return;
            }

            if (!vm.user.valiCode) {
                popup.alert("请输入验证码");
                return;
            }

            if (!vm.user.password) {
                popup.alert("请输入验密码");
                return;
            }
            if (!angular.equals(vm.user.password, vm.user.repassword)) {
                popup.alert("两次密码输入不一致");
                return;
            }
            if (!vm.agree) {
                popup.alert("您需要同意用户条款");
                return;
            }
            xhr.get('HealthInquiry/com/user/register', vm.user).then(function(result) {
                vm.user = result.data;
                vm.user.name = "";
                vm.user.email = "";
                localStore.save('user', vm.user);


                $state.go('register-doc-info', {
                    userId: vm.user.id
                });
            });
        }


    }

    function registerDocInfoCtrl($scope, $stateParams, xhr, localStore, $state, popup) {
        var vm = $scope.vm = {};
        $scope.vm.user = localStore.get('user');
        console.log(vm.user)

        // vm.user.branchName="asdasd";

        $scope.go = function(router) {
            $state.go(router)
        }


        $scope.register = function() {
            vm.user.deptPhone = vm.user.deptPhone_head + vm.user.deptPhone_body;
            vm.user.orderNo = 1;
            vm.user.userId = vm.user.id;
            console.log(vm.user)
            xhr.get("HealthInquiry/com/doctor/register", vm.user).then(function() {
                localStore.del("user");
                // popup.alert("提交成功");
                $state.go("register-doc-info-succ");
            });
        }

        $scope.$watch('vm.user', function(newValue, oldValue, scope) {
            localStore.save("user", vm.user);
        }, true);
    }


    function registerDocInfoHospitalCtrl($scope, xhr, $state, localStore, $stateParams) {

        var vm = $scope.vm = {};
        vm.hosList = [];

        vm.condition = {
            pageIndex: 0,
            pageSize: 20,
            // sortField:'',
            // sortOrder:'asc',
            name: ''
        }
        $scope.search = function() {
            return xhr.get("HealthInquiry/com/hospital/findByCondition", vm.condition)
                .then(function(result) {
                    // vm.hosList = result.data;
                    if (result.data.length <= 0) {
                        vm.nodata = true;
                    } else {
                        vm.hosList = vm.hosList.concat(result.data);
                        vm.nodata = false;
                    }

                });
        }


        $scope.doRefresh = function() {
            vm.condition.pageIndex = 0;
            vm.hosList = [];
            $scope.search().then(function() {
                $scope.$broadcast('scroll.refreshComplete');

            });

        }

        $scope.loadMore = function() {
            console.log(vm.condition.pageIndex);
            vm.condition.pageIndex++;
            $scope.search().then(function() {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });

        }

        $scope.selectHospital = function(hos) {
            console.log(hos)
            var user = localStore.get("user");
            user.hospitalName = hos.name;
            user.hospitalId = hos.id;
            localStore.save("user", user);
            var state = $stateParams.state;
            if (state) {
                if (angular.equals($stateParams.state, "userInfo-doc")) {
                    $state.go($stateParams.state, { edit: 1 });
                } else {
                    $state.go($stateParams.state);
                }
            } else {
                $state.go('register-doc-info');
            }
        }

        $scope.search();


        $scope.$watch('vm.condition.name', function(newValue, oldValue, scope) {
            $scope.doRefresh();
        });
    }

    function registerDocInfoDepartCtrl($window,$scope, xhr, localStore, $state, $stateParams) {
        var vm = $scope.vm = {};

        vm.condition = {
            pageIndex: 0,
            pageSize: 50,
            // sortField:'',
            // sortOrder:'asc',
            name: ''
        }
        $scope.search = function() {
            xhr.get("HealthInquiry/com/branch/findByCondition", vm.condition)
                .then(function(result) {
                    vm.list = result.data;
                });
        }


        $scope.selected = function(branch) {
            //查询子科室
            if (branch.hasChildren == 1) {
                vm.condition.parentId = branch.id;
                $scope.search();
            } else {
                var user = localStore.get("user");
                user.branchName = branch.name;
                user.branchId = branch.id;
                localStore.save("user", user);
                if ($stateParams.state) {
                    if (angular.equals($stateParams.state, "userInfo-doc")) {
                        $state.go($stateParams.state, { edit: 1 });
                    } else if (angular.equals($stateParams.state, "add-check")||angular.equals($stateParams.state, "edit-check")) {
                        $window.history.back();
                    }
                    else{
                        $state.go($stateParams.state);
                    }
                } else {
                    $state.go('register-doc-info');
                }

            }
        }

        $scope.search();


        $scope.$watch('vm.condition', function(newValue, oldValue, scope) {
            $scope.search();
        }, true);
    }


    function registerDocInfoPositionCtrl($scope, xhr, localStore, $state, $stateParams) {
        var vm = $scope.vm = {};


        vm.condition = {
            pageIndex: 0,
            pageSize: 50,
            // sortField:'',
            // sortOrder:'asc',
            name: ''
        }

        $scope.search = function() {

            xhr.get("HealthInquiry/com/professionTitle/findByCondition", vm.condition)
                .then(function(result) {
                    vm.list = result.data;
                });
        }


        $scope.selected = function(item) {
            var user = localStore.get("user");
            user.titleName = item.name;
            user.titleId = item.id;
            localStore.save("user", user);
            var state = $stateParams.state;
            console.log(state)
            if (state) {
                if (angular.equals($stateParams.state, "userInfo-doc")) {
                    $state.go($stateParams.state, { edit: 1 });
                } else {
                    $state.go($stateParams.state);
                }
            } else {
                $state.go('register-doc-info');
            }

        }

        $scope.search();


        $scope.$watch('vm.condition', function(newValue, oldValue, scope) {
            $scope.search();
        }, true);
    }


    function registerDocInfoSuccCtrl($scope, $state) {
        $scope.go = function(router) {
            $state.go(router);
        }
    }
})();

(function() {
    angular
        .module('ydApp.user', [])
        .config(function($stateProvider) {
            $stateProvider.state('tabs.user', {
                url: '/user-center',
                cache: false,
                nativeTransitions: null,
                views: {
                    'user-tab': {
                        controller: "userCenterCtrl",
                        templateUrl: 'views/userCenter/index-user.html'
                    }
                }
            });
            $stateProvider.state('tabs.user-doc', {
                cache: false,
                url: '/doc-center',
                views: {
                    'user-tab': {
                        controller: "docCenterCtrl",
                        templateUrl: 'views/userCenter/index-doc.html'
                    }
                }
            });
        })
        .controller("userCenterCtrl", userCenterCtrl)
        .controller("docCenterCtrl", docCenterCtrl);

    function userCenterCtrl($scope, $rootScope, $state, localStore, Cameranav, fileTransfer, $ionicLoading, xhr) {
        var vm = $scope.vm = {};
        vm.user = localStore.get('user');
        console.log(vm.user.headImgUrl)

        $scope.getAvatar = function() {
            Cameranav.getPicture(function(imgUri) {
                $ionicLoading.show({
                    template: '正在上传…'
                });
                fileTransfer.upload(imgUri, vm.user.id, function(data) {
                    if (data.successful) {
                        vm.user.headImgUrl = data.data.picUrl;

                        if (localStore.get("userType") == 1) {
                            url = "HealthInquiry/com/user/updateUserInfo";
                        } else {
                            url = "HealthInquiry/com/user/update"
                        }
                        xhr.get(url, vm.user).then(function(result) {
                            localStore.save("user", vm.user);
                            $ionicLoading.hide();
                        }).then(function(result) {
                            $ionicLoading.show({
                                template: '上传失败'
                            });
                            $ionicLoading.hide();
                        });

                    }
                    else{
                        $ionicLoading.hide();
                    }
                })
            })
        }
    }


    function docCenterCtrl($scope, $state, localStore) {
        var vm = $scope.vm = {};
        vm.user = localStore.get('user');
    }

})();

(function() {
    angular
        .module('ydApp.user.center', [])
        .config(function($stateProvider) {
            //个人信息
            $stateProvider.state('userInfo', {
                url: '/userInfo',
                cache: false,
                controller: 'userInfoCtrl',
                templateUrl: 'views/userCenter/user-info.html'
            });

            //医生信息
            $stateProvider.state('userInfo-doc', {
                url: '/doctorInfo/:edit',
                cache: false,
                controller: 'userInfoCtrl',
                templateUrl: 'views/userCenter/doctor-info.html'
            });


            //我的账户
            $stateProvider.state('userAccountset', {
                url: '/userAccountSet',
                cache: false,
                controller: 'accountSetCtrl',
                templateUrl: 'views/userCenter/account-set-user.html'
            });

            //我的账户医生版
            $stateProvider.state('docAccountset', {
                url: '/docAccountSet',
                cache: false,
                controller: 'docAccountSetCtrl',
                templateUrl: 'views/userCenter/account-set-doc.html'
            });

            //我的消息
            $stateProvider.state('message', {
                url: '/message',
                cache: false,
                controller: 'messageCtrl',
                templateUrl: 'views/userCenter/message.html'
            });

            //消息详情
            $stateProvider.state('messageDetail', {
                url: '/messageDetail/:id?content?sendTimeString?sendUserId',
                cache: false,
                controller: 'messageDetailCtrl',
                templateUrl: 'views/userCenter/message-detail.html'
            });

            //意见反馈
            $stateProvider.state('advice', {
                url: '/advice',
                cache: false,
                controller: 'adviceCtrl',
                templateUrl: 'views/userCenter/advice.html'
            });

            // 意见反馈成功
            $stateProvider.state('adviceOk', {
                url: '/adviceOk',
                cache: false,
                controller: 'adviceCtrl',
                templateUrl: 'views/userCenter/advice-ok.html'
            });

            // 重置密码
            $stateProvider.state('resetPwd', {
                url: '/resetPwd',
                cache: false,
                controller: 'resetPwdCtrl',
                templateUrl: 'views/userCenter/reset-pwd.html'
            });

            // 关于
            $stateProvider.state('about', {
                url: '/about',
                cache: false,
                controller: 'aboutCtrl',
                templateUrl: 'views/userCenter/about.html'
            });

            //免责申明
            $stateProvider.state('declare', {
                url: '/declare.html',
                cache: true,
                controller: 'aboutCtrl',
                templateUrl: 'views/userCenter/declare.html'
            })

            // 版本介绍
            $stateProvider.state('version', {
                url: '/version',
                cache: false,
                controller: 'versionCtrl',
                templateUrl: 'views/userCenter/version.html'
            });

            //常见问题
            $stateProvider.state('qustion', {
                url: '/qustion',
                cache: false,
                controller: 'qustionCtrl',
                templateUrl: 'views/userCenter/qustion.html'
            });

            //问题详情
            $stateProvider.state('qustionDetail', {
                url: '/qustionDetail/:id',
                cache: false,
                controller: 'qustionDetailCtrl',
                templateUrl: 'views/userCenter/qustion-detail.html'
            });

            //开通会员
            $stateProvider.state('vipIndex', {
                url: '/vipIndex',
                cache: false,
                controller: 'vipCtrl',
                templateUrl: 'views/userCenter/vip-index.html'
            });

            // 开通会员支付
            $stateProvider.state('vipPay', {
                url: '/vipPay',
                cache: false,
                controller: 'vipCtrl',
                templateUrl: 'views/userCenter/vip-pay.html'
            });

            // 开通会员支付成功
            $stateProvider.state('vipOk', {
                url: '/vipOk',
                cache: false,
                controller: 'versionCtrl',
                templateUrl: 'views/userCenter/vip-ok.html'
            });

            //我的账户
            $stateProvider.state('account', {
                url: '/account',
                cache: false,
                controller: 'accountCtrl',
                templateUrl: 'views/userCenter/account.html'
            });

            // 账户记录
            $stateProvider.state('accountHistory', {
                url: '/accountHistory',
                cache: false,
                controller: 'accountHistoryCtrl',
                templateUrl: 'views/userCenter/account-history.html'
            });

            // 充值
            $stateProvider.state('recharge', {
                url: '/recharge',
                cache: false,
                controller: 'rechargeCtrl',
                templateUrl: 'views/userCenter/recharge.html'
            });

            // 充值成功
            $stateProvider.state('rechargeOk', {
                url: '/rechargeOk',
                cache: false,
                controller: 'versionCtrl',
                templateUrl: 'views/userCenter/recharge-ok.html'
            });

            //  充值失败
            $stateProvider.state('rechargeFail', {
                url: '/rechargeFail',
                cache: false,
                controller: 'versionCtrl',
                templateUrl: 'views/userCenter/recharge-fail.html'
            });

            // 充值
            $stateProvider.state('message-info', {
                url: '/message-info',
                cache: false,
                controller: 'messageInfoCtrl',
                templateUrl: 'views/userCenter/message-info.html'
            });

            // 提现
            $stateProvider.state('fetch', {
                url: '/fetch/:bankType?code',
                cache: false,
                controller: 'fetchCtrl',
                templateUrl: 'views/userCenter/fetch.html'
            });
            //银行卡列表
            $stateProvider.state('card', {
                url: '/card',
                cache: false,
                controller: 'cardCtrl',
                templateUrl: 'views/userCenter/card.html'
            });
            //添加银行卡
            $stateProvider.state('card-add', {
                url: '/card-add',
                cache: false,
                controller: 'cardAddCtrl',
                templateUrl: 'views/userCenter/card-add.html'
            });

        })
        // .filter("actionMode", function(input) {
        //     return function(input) {
        //         var rValue;
        //         switch (input) {
        //             case 0:
        //                 rValue = "充值";
        //                 break;
        //             case 1:
        //                 rValue = "消费";
        //                 break;
        //             case 2:
        //                 rValue = "提现";
        //                 break;
        //             default:
        //                 rValue = "";

    //         }
    //         return rValue;
    //     }
    // })
    // .controller("userCenterCtrl", userCenterCtrl)
    .controller("userInfoCtrl", userInfoCtrl)
        // .controller("docCenterCtrl", docCenterCtrl)
        .controller("messageCtrl", messageCtrl)
        .controller("aboutCtrl", aboutCtrl)
        .controller("resetPwdCtrl", resetPwdCtrl)
        .controller("versionCtrl", resetPwdCtrl)
        .controller("docAccountSetCtrl", docAccountSetCtrl)
        .controller("messageDetailCtrl", messageDetailCtrl)
        .controller("resetPwdCtrl", resetPwdCtrl)
        .controller("qustionCtrl", qustionCtrl)
        .controller("qustionDetailCtrl", qustionDetailCtrl)
        .controller("messageInfoCtrl", messageInfoCtrl)
        .controller("vipCtrl", vipCtrl)
        .controller("accountCtrl", accountCtrl)
        //账户设置
        .controller("accountSetCtrl", accountSetCtrl)
        .controller("accountHistoryCtrl", accountHistoryCtrl)
        .controller("adviceCtrl", adviceCtrl)
        .controller("rechargeCtrl", rechargeCtrl)
        .controller("fetchCtrl", fetchCtrl)
        .controller('cardCtrl', cardCtrl)
        .controller('cardAddCtrl', cardAddCtrl);



    // function userCenterCtrl($scope, $state) {
    //     var vm = $scope.vm = {};

    //     $scope.go = function(state) {
    //         $state.go(state);
    //     }
    // }


    function userInfoCtrl($scope, $stateParams, localStore, xhr, $state, popup, Cameranav, fileTransfer, $ionicLoading, xhr, $cordovaToast) {

        var vm = $scope.vm = {};
        if ($stateParams.edit) {
            vm.edit = true;
        } else {
            vm.edit = false;
        }
        vm.user = localStore.get("user");
        $scope.logout = function() {
            localStore.del("user");
            console.log(localStore.get("user"));
            $scope.updateOnLine(0);
            $state.go("login");
        }

        $scope.save = function() {
            console.log("save user info")
            if (localStore.get("userType") == 2) {
                popup.confirm("您正在修改个人信息，回复咨询、鉴定及金额提现等服务将暂停使用，是否继续修改？")
                    .then(function(res) {
                        if (res) {
                            $scope.update();
                        }
                    });
            } else {
                $scope.update();

            }

        }

        $scope.update = function() {
            console.log("update vm.user")
            console.log(JSON.stringify(vm.user));
            var url = vm.user.userType == 1 ? "HealthInquiry/com/user/updateUserInfo" : "HealthInquiry/com/doctor/update";
            xhr.get(url, vm.user)
                .then(function() {
                    vm.edit = false;
                    $cordovaToast.showShortCenter("修改成功");
                    localStore.save("user", vm.user);
                });
        }

        $scope.go = function(router, state) {
            $state.go(router, { state: state });
        }


        $scope.goDocInfo = function(router, state) {
            console.log("router:" + router)
            $state.go(router, { state: state, edit: 1 })
        }

        $scope.updateOnLine = function(isOnline) {
            console.log("isOnline:" + isOnline)
            vm.user = localStore.get("user");
            console.log(vm.user)
            vm.user.isOnline = isOnline;
            xhr.get("HealthInquiry/com/user/updateIsonline", {
                id: vm.user.id,
                is_online: vm.user.isOnline
            }).then(function(result) {
                // $cordovaToast.showShortCenter("更新状态成功");
                if (isOnline == 0) {
                    localStore.del("user");
                    localStore.del("userType");
                } else {
                    localStore.save('user', vm.user);
                }
            });
        }



        $scope.getAvatar = function() {
            vm.user = localStore.get("user");
            Cameranav.getPicture(function(imgUri) {
                $ionicLoading.show({
                    template: '正在上传…'
                });
                fileTransfer.upload(imgUri, vm.user.id, function(data) {
                    if (data.successful) {
                        vm.user.headImgUrl = data.data.picUrl;
                        localStore.save("user", vm.user);
                        $scope.update();
                        // xhr.get(url, vm.user).then(function(result) {
                        //     localStore.save("user", vm.user);
                        //     $ionicLoading.hide();
                        // }).then(function(result) {
                        //     $ionicLoading.show({
                        //         template: '上传失败'
                        //     });
                        //     $ionicLoading.hide();
                        // });
                        $ionicLoading.hide();

                    } else {
                        $ionicLoading.hide();

                    }
                })
            })
        }


    }

    // function docCenterCtrl($scope, $state, localStore) {
    //     var vm = $scope.vm = {};

    //     vm.go = function(state) {
    //         $state.go(state);
    //     }
    // }


    function docAccountSetCtrl($scope, $state, localStore, xhr, $cordovaToast) {
        var vm = $scope.vm = {};
        vm.user = localStore.get('user');
        vm.telphone = vm.user.code;

        $scope.logout = function() {
            console.log(localStore.get("user"));
            $scope.updateOnLine(0);
            localStore.del("user");
            localStore.del('userType');
            $state.go("login");
        }


        // $scope.getDoc = function() {
        //     console.log(vm.user.id);
        //     // if (vm.user.isOnline == 0) {
        //     //         vm.user.isOnline = 1;
        //     //     }
        //     xhr.get('HealthInquiry/com/doctor/findById', { id: vm.user.id }).then(function(result) {
        //         vm.user = result.data;
        //         vm.user.userType = 2;
        //         vm.user.code = vm.telphone;
        //         if (vm.user.isOnline == 0) {
        //             vm.user.isOnline = 1;
        //         }
        //         console.log(vm.user);
        //         localStore.save("user", vm.user);
        //     });
        // }


        $scope.updateOnLine = function(isOnline) {
            vm.user = localStore.get("user");
            if (!vm.user) {
                return;
            }

            vm.user.isOnline = isOnline;
            xhr.get("HealthInquiry/com/user/updateIsonline", {
                id: vm.user.id,
                is_online: vm.user.isOnline
            }).then(function(result) {
                // $cordovaToast.showShortCenter("更新状态成功");
                if (isOnline == 0) {
                    localStore.del("user");
                } else {
                    localStore.save('user', vm.user);
                }
            });
        }

        $scope.updateCallCount = function() {
            // vm.user.callCount=callCount;
            xhr.get("HealthInquiry/com/doctor/updateCallCount", {
                id: vm.user.id,
                callCount: vm.user.callCount
            }).then(function(result) {
                localStore.save('user', vm.user);
                $cordovaToast.showShortCenter("更新成功");

            });
        }

        // $scope.getDoc();

    }

    function accountSetCtrl($scope, $state, localStore, xhr, $cordovaToast) {
        var vm = $scope.vm = {};
        vm.user = localStore.get('user');
        $scope.go = function(router) {
            $state.go(router);
        }

        // $scope.getUser = function() {
        //     xhr.get('HealthInquiry/com/user/findById', { id: vm.user.id }).then(function(result) {
        //         vm.user = result.data;
        //         vm.user.userType = 1;
        //         localStore.save("userType",vm.user.userType);
        //         vm.user.isOnline = vm.user.is_online;
        //         if (vm.user.isOnline == 0) {
        //             vm.user.isOnline = 1;
        //         }
        //         console.log(vm.user);
        //         localStore.save("user", vm.user);
        //     });
        // }

        $scope.downloadImg = function(img) {
            return config.api + "HealthInquiry" + img;
        }

        $scope.updateOnLine = function(status) {
            vm.user.isOnline = status;
            xhr.get('HealthInquiry/com/user/updateIsonline', {
                id: vm.user.id,
                is_online: status
            }).then(function(result) {
                // $cordovaToast.showShortCenter("更新状态成功");
                //离线
                console.log("status:" + status);
                if (status == 0) {
                    localStore.del("user");
                } else {
                    localStore.save('user', vm.user);
                }
            });;
        }



        $scope.logout = function() {
                localStore.del("user");
                localStore.del('localStore');
                $scope.updateOnLine(0)
                $state.go("login");
            }
            // $scope.getUser();
    }

    function messageCtrl($scope, $state, localStore, xhr, $cordovaToast) {
        var vm = $scope.vm = {
            nodata: false,
            list: []
        };
        vm.user = localStore.get("user");

        vm.condition = {
            pageIndex: 0,
            pageSize: 10,
            userId: vm.user.id
                // sortField:'',
                // sortOrder:'asc',
        }
        vm.showMsg = false;

        $scope.doRefresh = function() {
            vm.condition.pageIndex = 0;
            vm.list = [];
            $scope.query().then(function() {
                $scope.$broadcast('scroll.refreshComplete');
            });

        }

        $scope.loadMore = function() {
            console.log(vm.condition.pageIndex);
            vm.condition.pageIndex++;
            $scope.query().then(function() {
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });

        }


        $scope.query = function() {
            return xhr.get('HealthInquiry/com/sysMessage/findByCondition', vm.condition).then(function(result) {
                if (result.data.length <= 0) {
                    vm.nodata = true;
                } else {
                    vm.list = vm.list.concat(result.data);
                    vm.nodata = false;
                }
            });
        }

        $scope.showMessage = function(message) {
            xhr.get("HealthInquiry/com/sysMessage/readById", {
                msgId: message.id,
                userId: vm.user.id
            }).then(function(result) {
                $state.go("messageDetail", {
                    id: message.id,
                    sendUserId: message.sendUserId,
                    content: message.content,
                    sendTimeString: message.sendTimeString
                })
            });

        }


        $scope.readAll = function() {
            xhr.get("HealthInquiry/com/sysMessage/readAll", {
                userId: vm.user.id
            }).then(function() {
                vm.showMsg = false;
                $cordovaToast.showShortCenter("操作成功");
                $scope.query();
            });
        }


        $scope.deleteAll = function() {
            xhr.get("HealthInquiry/com/sysMessage/deleteAll", {
                userId: vm.user.id
            }).then(function() {
                vm.showMsg = false;
                $cordovaToast.showShortCenter("操作成功");
                $scope.query();
            });
        }

        $scope.query();


    }

    function messageDetailCtrl($scope, xhr, $stateParams) {
        var vm = $scope.vm = {};
        vm.message = {
            id: $stateParams.id,
            content: $stateParams.content,
            sendUserId: $stateParams.sendUserId,
            sendTimeString: $stateParams.sendTimeString
        }
    }


    function resetPwdCtrl($scope, xhr, $stateParams, popup, $timeout, $state, $ionicHistory, $cordovaToast, localStore) {
        var vm = $scope.vm = {};
        vm.enable = true;


        $scope.getCode = function() {
            if (!vm.enable) {
                return;
            }
            if (vm.code) {
                xhr.get('HealthInquiry/com/sms/send', { phone: vm.code }).then(function(result) {
                    vm.enable = false;
                    vm.time = 60,
                        $scope.timeInteval();
                });
            } else {
                popup.alert("请输入手机号码");
            }

        }

        $scope.timeInteval = function() {
            vm.time--;
            if (vm.time > 0) {
                $timeout($scope.timeInteval, 1000);
            } else {
                vm.enable = true;
            }
        }


        $scope.resetPwd = function() {
            if (!vm.code) {
                popup.alert("请输入手机号码");
                return;
            }

            if (!vm.valiCode) {
                popup.alert("请输入验证码");
                return;
            }

            if (!vm.password) {
                popup.alert("请输入验密码");
                return;
            }
            if (!angular.equals(vm.password, vm.repassword)) {
                popup.alert("两次密码输入不一致");
                return;
            }

            xhr.get("HealthInquiry/com/user/updatepwd", {
                code: vm.code,
                valiCode: vm.valiCode,
                password: vm.password
            }).then(function(result) {
                // $cordovaToast.showShortCenter(result.resultMsg);
                // popup.alert(result.resultMsg);
                // $ionicHistory.goBack();
                localStore.save("message", {
                    title: '修改密码',
                    content: '您已修改成功',
                    back: 'tabs.user'
                })
                $state.go("message-info");
            });
        }
    }

    function adviceCtrl($scope, $state, xhr, popup, $ionicHistory, localStore) {
        var vm = $scope.vm = {};

        $scope.save = function() {
            xhr.get("HealthInquiry/com/feedback/saveOrUpdate", {
                email: vm.email,
                content: vm.content,
                phone: vm.phone
            }).then(function(result) {
                localStore.save("message", {
                    title: '意见反馈',
                    content: '您的建议我们已经收到,非常感谢!',
                    back: 'tabs.user'
                })
                $state.go("message-info");
            })
        }
    }


    function aboutCtrl($cordovaInAppBrowser, $scope) {
        var vm = $scope.vm = {
            'declareUrl': config.api + "HealthInquiry/view/health/disclaimer_show.jsp"
        }
        console.log($scope.vm.declareUrl)
        var options = {
            location: 'no',
            clearcache: 'no',
            toolbar: 'yes'
        };
        $scope.open = function() {
            $cordovaInAppBrowser.open(config.api + "HealthInquiry/view/health/disclaimer_show.jsp", '_blank', options);
        }
    }

    function qustionCtrl(xhr, $scope, $state) {
        var vm = $scope.vm = {};
        vm.page = 0;
        xhr.get("HealthInquiry/com/question/findByCondition", {
            page: vm.page
        }).then(function(result) {
            vm.list = result.data;
        });

        $scope.toDetail = function(q) {
            $state.go("qustionDetail", {
                id: q.id
            });
        }
    }

    function qustionDetailCtrl($scope, xhr, $stateParams) {
        var vm = $scope.vm = {};
        xhr.get("HealthInquiry/com/question/findById", {
            id: $stateParams.id
        }).then(function(result) {
            vm.qustion = result.data;
        });
    }


    function messageInfoCtrl($scope, localStore) {
        var vm = $scope.vm = {};
        vm.message = localStore.get("message");
        vm.message = angular.isUndefined(vm.message) ? {} : vm.message;
    }


    function vipCtrl($scope, $cordovaToast, pay, localStore, xhr, popup, $state) {
        var vm = $scope.vm = {};
        vm.user = localStore.get("user");
        vm.money = 100;
        $scope.payVip = function() {
            xhr.get("HealthInquiry/com/user/openVip", {
                userId: vm.user.id,
                money: 100
            }).then(function(res) {
                console.log(res);
                popup.alert(res.resultMsg);
                $state.go('tabs.user');
            }, function(err) {
                $state.go("recharge");
            });
        }
    }

    function accountCtrl($scope, $cordovaToast, xhr, localStore, $state) {

        var vm = $scope.vm = {};
        vm.userType = localStore.get("userType")
        vm.user = localStore.get("user");

        xhr.get("HealthInquiry/com/account/findBalanceByUserId", {
            userId: localStore.get("user").id
        }).then(function(result) {
            vm.balance = result.data.balance;
        });


    }


    function accountHistoryCtrl($scope, xhr, localStore) {
        var vm = $scope.vm = {};
        vm.user = localStore.get("user");
        $scope.query = function() {
            xhr.get("HealthInquiry/com/accountDetail/findByCondition", {
                userId: vm.user.id
            }).then(function(result) {
                vm.list = result.data;
                angular.forEach(vm.list, function(value, key) {
                    value.time = value.actionTimeString.substring(0, 10);
                });
                console.log(result);
            });
        }
        $scope.query();
    }

    function rechargeCtrl($scope, xhr, localStore, pay, $state) {
        var vm = $scope.vm = {};
        vm.money = 100;
        vm.user = localStore.get("user");
        $scope.pay = function() {
            var reg = /^\d+(\.\d+)?$/;
            if (!reg.test(vm.money) || vm.money <= 0) {
                $cordovaToast.showShortCenter("请输入正确的金额");
                return;
            }
            xhr.get("HealthInquiry/com/alipay/getOders", {
                userId: vm.user.id,
                money: vm.money
            }).then(function(result) {
                var orderNo = result.data.orderNo;
                pay.alipay("余额充值", "余额充值", vm.money, orderNo, function(result) {
                    $state.go('rechargeOk')
                }, function(error) {

                });
            });
        }
    }


    function fetchCtrl($scope, xhr, localStore, $state, popup, $stateParams) {
        var vm = $scope.vm = {};
        vm.model = {};
        vm.user = localStore.get("user");
        vm.card = {
                'code': $stateParams.code,
                'bankType': $stateParams.bankType
            }
            //查询余额
        xhr.get("HealthInquiry/com/account/findBalanceByUserId", {
            userId: vm.user.id
        }).then(function(result) {
            vm.balance = result.data.balance;
        });

        console.log(vm.card);

        //传了银行卡信息
        if (vm.card.code && vm.card.bankType) {

        }
        //没有传
        else {
            xhr.get('HealthInquiry/com/accountCard/findByUserId', {
                'userId': vm.user.id
            }).then(function(res) {
                if (res.data.length <= 0) {
                    popup.alert('您还没有绑定银行卡，请至少先绑定一张银行卡');
                    $state.go('card-add');
                } else {
                    vm.card = res.data[0];
                }
            });
        }

        //提现申请
        $scope.save = function() {
            var reg = /^[0-9]+$/;
            if (!reg.test(vm.model.money) || vm.model.money <= 0) {
                alert("请输入正确的金额");
                return;
            }
            vm.model.userId = vm.user.id;
            xhr.get("HealthInquiry/com/account/withdraw", vm.model).then(function(res) {
                if (res.successful) {
                    popup.alert(res.resultMsg);
                    $state.go("account");
                }
            });
        }

        $scope.toCard = function() {
            $state.go('card');
        }

    }

    function cardCtrl($scope, xhr, localStore, $state, $cordovaToast, popup) {
        var vm = $scope.vm = {};
        vm.user = localStore.get("user");
        $scope.init = function() {
            xhr.get('HealthInquiry/com/accountCard/findByUserId', {
                'userId': vm.user.id
            }).then(function(res) {
                vm.cardList = res.data;
            });
        }

        $scope.toFetch = function(card) {
            $state.go("fetch", {
                bankType: card.bankType,
                code: card.code
            });
        }
        $scope.init();

        $scope.delCard = function(card) {
            popup.confirm("是否删除该卡片").then(function(res) {
                if (res) {
                    xhr.get("HealthInquiry/com/accountCard/delete", {
                        'id': card.id
                    }).then(function(res) {
                        if (res.successful) {
                            $cordovaToast.showShortCenter("删除成功");
                            $scope.init();
                        }
                    });
                }
            });

        }
    }

    function cardAddCtrl($scope, xhr, localStore, $state, $timeout, popup) {
        var vm = $scope.vm = {};
        vm.user = localStore.get("user");
        vm.agree = false;
        vm.model = {
            userId: vm.user.id,
            phone: vm.user.code,
            // name: vm.user.name,
            bankType: "中国银行"
        };
        vm.enable = true;


        $scope.getCode = function() {
            if (!vm.enable) {
                return;
            }
            if (vm.model.phone) {
                xhr.get('HealthInquiry/com/sms/send', {
                    phone: vm.model.phone
                }).then(function(result) {
                    vm.time = 60;
                    $scope.timeInteval();
                    vm.enable = false;
                });
            } else {
                popup.alert("请输入手机号码");
            }

        }

        $scope.timeInteval = function() {
            vm.time--;
            if (vm.time > 0) {
                $timeout($scope.timeInteval, 1000);
            } else {
                vm.enable = true;
            }
        }


        $scope.saveCard = function() {

            // var reg = /^[0-9]+$/;
            if (!vm.model.name) {
                popup.alert("请输入姓名");
                return;
            }
            var reg = /^\d{14,22}$/;

            if (!reg.test(vm.model.code)) {
                popup.alert("请输入正确的银行卡号");
                return;
            }
            reg = /^1\d{10}$/;
            if (!reg.test(vm.model.phone)) {
                popup.alert("请输入正确的手机号");
                return;
            }
            if (!vm.model.valiCode) {
                popup.alert("请输入验证码");
                return;
            }
            if (!vm.agree) {
                popup.alert("请同意服务协议");
                return;
            }
            xhr.get("HealthInquiry/com/accountCard/saveOrUpdate", vm.model).then(function(res) {
                if (res.successful) {
                    popup.alert("保存成功");
                    $state.go("card");
                } else {

                }
            });

        }

    }

})();
